Copyright © 1996-2013 John W. Eaton.
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
| [Top] | [Contents] | [Index] | [ ? ] |
This manual documents how to run, install and port GNU Octave, as well as its new features and incompatibilities, and how to report bugs. It corresponds to GNU Octave version 3.8.2.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave was originally intended to be companion software for an undergraduate-level textbook on chemical reactor design being written by James B. Rawlings of the University of Wisconsin-Madison and John G. Ekerdt of the University of Texas.
Clearly, Octave is now much more than just another ‘courseware’ package with limited utility beyond the classroom. Although our initial goals were somewhat vague, we knew that we wanted to create something that would enable students to solve realistic problems, and that they could use for many things other than chemical reactor design problems. We find that most students pick up the basics of Octave quickly, and are using it confidently in just a few hours.
Although it was originally intended to be used to teach reactor design, it has been used in several other undergraduate and graduate courses in the Chemical Engineering Department at the University of Texas, and the math department at the University of Texas has been using it for teaching differential equations and linear algebra as well. More recently, Octave has been used as the primary computational tool for teaching Stanford’s online Machine Learning class (ml-class.org) taught by Andrew Ng. Tens of thousands of students participated in the course.
If you find Octave useful, please let us know. We are always interested to find out how Octave is being used.
Virtually everyone thinks that the name Octave has something to do with music, but it is actually the name of one of John W. Eaton’s former professors who wrote a famous textbook on chemical reaction engineering, and who was also well known for his ability to do quick ‘back of the envelope’ calculations. We hope that this software will make it possible for many people to do more ambitious computations just as easily.
Everyone is encouraged to share this software with others under the terms of the GNU General Public License (see section GNU GENERAL PUBLIC LICENSE). You are also encouraged to help make Octave more useful by writing and contributing additional functions for it, and by reporting any problems you may have.
| Acknowledgements | ||
| Citing Octave in Publications | ||
| How You Can Contribute to Octave | ||
| Distribution |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Many people have contributed to Octave’s development. The following people have helped code parts of Octave or aided in various other ways (listed alphabetically).
| Ben Abbott | Andy Adler | Adam H. Aitkenhead |
| Giles Anderson | Joel Andersson | Muthiah Annamalai |
| Markus Appel | Branden Archer | Marco Atzeri |
| Shai Ayal | Roger Banks | Ben Barrowes |
| Alexander Barth | David Bateman | Heinz Bauschke |
| Julien Bect | Roman Belov | Karl Berry |
| David Billinghurst | Don Bindner | Jakub Bogusz |
| Moritz Borgmann | Paul Boven | Richard Bovey |
| John Bradshaw | Marcus Brinkmann | Max Brister |
| Remy Bruno | Clemens Buchacher | Ansgar Burchard |
| Marco Caliari | Daniel Calvelo | John C. Campbell |
| Juan Pablo Carbajal | Jean-Francois Cardoso | Joao Cardoso |
| Larrie Carr | David Castelow | Vincent Cautaerts |
| Clinton Chee | Albert Chin-A-Young | Carsten Clark |
| Catalin Codreanu | J. D. Cole | Martin Costabel |
| Michael Creel | Richard Crozier | Jeff Cunningham |
| Martin Dalecki | Jacob Dawid | Jorge Barros de Abreu |
| Carlo de Falco | Thomas D. Dean | Philippe Defert |
| Bill Denney | Fabian Deutsch | Christos Dimitrakakis |
| Pantxo Diribarne | Vivek Dogra | John Donoghue |
| David M. Doolin | Carnë Draug | Pascal A. Dupuis |
| John W. Eaton | Dirk Eddelbuettel | Pieter Eendebak |
| Paul Eggert | Stephen Eglen | Peter Ekberg |
| Rolf Fabian | Gunnar Farnebäck | Stephen Fegan |
| Ramon Garcia Fernandez | Torsten Finke | Jose Daniel Munoz Frias |
| Brad Froehle | Castor Fu | Eduardo Gallestey |
| Walter Gautschi | Klaus Gebhardt | Driss Ghaddab |
| Nicolo Giorgetti | Arun Giridhar | Michael D. Godfrey |
| Michael Goffioul | Glenn Golden | Tomislav Goles |
| Keith Goodman | Brian Gough | Steffen Groot |
| Etienne Grossmann | David Grundberg | Kyle Guinn |
| Peter Gustafson | Kai Habel | Patrick Häcker |
| William P. Y. Hadisoeseno | Jaroslav Hajek | Benjamin Hall |
| Kim Hansen | Søren Hauberg | Dave Hawthorne |
| Daniel Heiserer | Martin Helm | Stefan Hepp |
| Martin Hepperle | Jordi Gutiérrez Hermoso | Yozo Hida |
| Ryan Hinton | Roman Hodek | A. Scottedward Hodel |
| Richard Allan Holcombe | Tom Holroyd | David Hoover |
| Kurt Hornik | Christopher Hulbert | Cyril Humbert |
| John Hunt | Teemu Ikonen | Alan W. Irwin |
| Geoff Jacobsen | Mats Jansson | Cai Jianming |
| Steven G. Johnson | Heikki Junes | Matthias Jüschke |
| Atsushi Kajita | Jarkko Kaleva | Mohamed Kamoun |
| Lute Kamstra | Fotios Kasolis | Thomas Kasper |
| Joel Keay | Mumit Khan | Paul Kienzle |
| Aaron A. King | Erik Kjellson | Arno J. Klaassen |
| Alexander Klein | Geoffrey Knauth | Heine Kolltveit |
| Ken Kouno | Kacper Kowalik | Daniel Kraft |
| Nir Krakauer | Aravindh Krishnamoorthy | Oyvind Kristiansen |
| Artem Krosheninnikov | Piotr Krzyzanowski | Volker Kuhlmann |
| Tetsuro Kurita | Philipp Kutin | Miroslaw Kwasniak |
| Rafael Laboissiere | Kai Labusch | Claude Lacoursiere |
| Walter Landry | Bill Lash | Dirk Laurie |
| Maurice LeBrun | Friedrich Leisch | Thorsten Liebig |
| Jyh-miin Lin | Timo Lindfors | Benjamin Lindner |
| Ross Lippert | David Livings | Sebastien Loisel |
| Erik de Castro Lopo | Massimo Lorenzin | Emil Lucretiu |
| Hoxide Ma | Colin Macdonald | James Macnicol |
| Jens-Uwe Mager | Rob Mahurin | Alexander Mamonov |
| Ricardo Marranita | Orestes Mas | Axel Mathéi |
| Makoto Matsumoto | Tatsuro Matsuoka | Christoph Mayer |
| Laurent Mazet | G. D. McBain | Ronald van der Meer |
| Júlio Hoffimann Mendes | Ed Meyer | Thorsten Meyer |
| Petr Mikulik | Mike Miller | Stefan Monnier |
| Antoine Moreau | Kai P. Mueller | Hannes Müller |
| Victor Munoz | Iain Murray | Carmen Navarrete |
| Todd Neal | Philip Nienhuis | Al Niessner |
| Felipe G. Nievinski | Rick Niles | Takuji Nishimura |
| Kai Noda | Patrick Noffke | Eric Norum |
| Krzesimir Nowak | Michael O’Brien | Peter O’Gorman |
| Thorsten Ohl | Arno Onken | Valentin Ortega-Clavero |
| Luis F. Ortiz | Carl Osterwisch | Janne Olavi Paanajärvi |
| Scott Pakin | Gabriele Pannocchia | Sylvain Pelissier |
| Per Persson | Primozz Peterlin | Jim Peterson |
| Danilo Piazzalunga | Nicholas Piper | Elias Pipping |
| Robert Platt | Hans Ekkehard Plesser | Tom Poage |
| Orion Poplawski | Ondrej Popp | Jef Poskanzer |
| Francesco Potortì | Konstantinos Poulios | Jarno Rajahalme |
| James B. Rawlings | Eric S. Raymond | Balint Reczey |
| Joshua Redstone | Lukas Reichlin | Michael Reifenberger |
| Jens Restemeier | Anthony Richardson | Jason Riedy |
| E. Joshua Rigler | Sander van Rijn | Petter Risholm |
| Matthew W. Roberts | Peter Rosin | Andrew Ross |
| Fabio Rossi | Mark van Rossum | Joe Rothweiler |
| Kevin Ruland | Kristian Rumberg | Ryan Rusaw |
| Olli Saarela | Toni Saarela | Juhani Saastamoinen |
| Radek Salac | Ben Sapp | Aleksej Saushev |
| Alois Schlögl | Michel D. Schmid | Julian Schnidder |
| Nicol N. Schraudolph | Sebastian Schubert | Ludwig Schwardt |
| Thomas L. Scofield | Daniel J. Sebald | Dmitri A. Sergatskov |
| Vanya Sergeev | Baylis Shanks | Andriy Shinkarchuck |
| Robert T. Short | Joseph P. Skudlarek | John Smith |
| Julius Smith | Shan G. Smith | Peter L. Sondergaard |
| Joerg Specht | Quentin H. Spencer | Christoph Spiel |
| Richard Stallman | Russell Standish | Brett Stewart |
| Doug Stewart | Jonathan Stickel | Judd Storrs |
| Thomas Stuart | Ivan Sutoris | John Swensen |
| Daisuke Takago | Ariel Tankus | Falk Tannhäuser |
| Duncan Temple Lang | Matthew Tenny | Kris Thielemans |
| Georg Thimm | Corey Thomasson | Olaf Till |
| Christophe Tournery | Thomas Treichl | Karsten Trulsen |
| David Turner | Frederick Umminger | Utkarsh Upadhyay |
| Stefan van der Walt | Peter Van Wieren | James R. Van Zandt |
| Risto Vanhanen | Gregory Vanuxem | Mihas Varantsou |
| Ivana Varekova | Sébastien Villemot | Daniel Wagenaar |
| Thomas Walter | Andreas Weber | Olaf Weber |
| Thomas Weber | Rik Wehbring | Bob Weigel |
| Andreas Weingessel | Martin Weiser | Michael Weitzel |
| David Wells | Fook Fah Yap | Sean Young |
| Michael Zeising | Federico Zenith | Alex Zvoleff |
Special thanks to the following people and organizations for supporting the development of Octave:
This project would not have been possible without the GNU software used in and to produce Octave.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In view of the many contributions made by numerous developers over many years
it is common courtesy to cite Octave in publications when it has been used
during the course of research or the preparation of figures. The
citation function can automatically generate a recommended citation
text for Octave or any of its packages. See the help text below on how to
use citation.
Display instructions for citing GNU Octave or its packages in publications.
When called without an argument, display information on how to cite the core GNU Octave system. When given a package name package, display information on citing the specific named package. Note that some packages may not yet have instructions on how to cite them.
The GNU Octave developers and its active community of package authors have invested a lot of time and effort in creating GNU Octave as it is today. Please give credit where credit is due and cite GNU Octave and its packages when you use them.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There are a number of ways that you can contribute to help make Octave a better system. Perhaps the most important way to contribute is to write high-quality code for solving new problems, and to make your code freely available for others to use. See section Contributing Guidelines, for detailed information on contributing new code.
If you find Octave useful, consider providing additional funding to continue its development. Even a modest amount of additional funding could make a significant difference in the amount of time that is available for development and support.
Donations supporting Octave development may be made on the web at https://my.fsf.org/donate/working-together/octave. These donations also help to support the Free Software Foundation
If you’d prefer to pay by check or money order, you can do so by sending a check to the FSF at the following address:
Free Software Foundation
51 Franklin Street, Suite 500
Boston, MA 02110-1335
USA
If you pay by check, please be sure to write “GNU Octave” in the memo field of your check.
If you cannot provide funding or contribute code, you can still help make Octave better and more reliable by reporting any bugs you find and by offering suggestions for ways to improve Octave. See section Known Causes of Trouble, for tips on how to write useful bug reports.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave is free software. This means that everyone is free to use it and free to redistribute it on certain conditions. Octave is not, however, in the public domain. It is copyrighted and there are restrictions on its distribution, but the restrictions are designed to ensure that others will have the same freedom to use and redistribute Octave that you have. The precise conditions can be found in the GNU General Public License that comes with Octave and that also appears in GNU GENERAL PUBLIC LICENSE.
To download a copy of Octave, please visit http://www.octave.org/download.html.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GNU Octaveは主に数値計算を意図した、ハイレベル言語であり、通常は線形、および非線形の代数、数値線形代数(numerical linear algebra)、統計分析を解決したり、その他の数値実験(numerical experiment)を行なうために使用されます。また、自動化されたデータ処理のための、バッチ指向言語としても使用されます。
最近まで、GNU Octaveは別ウィンドウでグラフィカルな結果を表示する、コマンドラインインターフェイスを提供していました。最新のバージョン(2013年後半にリリースされたバージョン3.8)は、デフォルトではグラフィカルユーザーインターフェイスも提供します。
GNU Octaveは自由に再頒布できるソフトウェアです。Free Software Foundationから公表されたGNU General Public Licenseの条件に基づき、あなたはこれを再頒布、かつ/または改変することができます。GPLは、このマニュアルのsee section GNU GENERAL PUBLIC LICENSEに含まれています。
このマニュアルはGNU Octaveのインストール、実行、使用に関する包括的なドキュメントを提供します。バグ報告やコードの寄贈については、追加のチャプターで説明します。
このドキュメントは、Octave バージョン3.8.2に対応します。
| 1.1 Running Octave | ||
| 1.2 Simple Examples | ||
| 1.3 Conventions |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
大部分のシステムでは、シェルコマンド‘octave’によりOctaveが起動されます。デフォルトでは、このコマンドによりグラフィカルユーザーインターフェイス(GUI)が起動します。このGUIの中の中央のウィンドウは、Octaveのコマンドラインインターフェイスです。Octaveは初期メッセージを表示してから、入力を受け取る準備ができたことを示すプロンプトを表示します。伝統的なコマンドラインインターフェイスを選択していた場合には、コマンドプロンプトだけが表示されます。どちらの場合でも、すぐにOctaveコマンドのタイプを開始できます。
問題が起きた場合、通常はControl-C(略記はC-c)をタイプすることにより、Octaveに割り込むことができます。C-cの名前は、<CTRL>を押したまま<c>を押すという事実が由来です。これを行なうことにより、通常はOctaveのプロンプトに戻ることができるでしょう。
Octaveを終了するには、Octaveのプロンプトでquit、または, exitとタイプします。
ジョブ制御をサポートするシステムでは、通常はC-zとタイプしてSIGTSTPシグナルを送ることにより、Octaveをサスペンドすることができます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
以降のチャプターでは、Octaveのもつすべての機能の詳細を説明しますが、その前にOctaveの能力を示すサンプルを見ておくことが助けになるかもしれません。
Octaveに触れるのが初めてならば、これらのサンプルを試して実際にOctaveを使ってみることから、Octaveの学習を開始することをおすすめします。‘octave:13>’のようにマークされたラインは、あなたがタイプして最後にエンターで終了するラインです。するとOctaveは答えを示すか、グラフを表示するでしょう。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveでは、基本的な数値計算を簡単に行うことができ、算術演算子(+,-,*,/)、べき乗(^)、対数と指数(log, exp)、三角関数(sin, cos, …)を認識します。さらにOctaveでの演算は実数に加えて虚数(i,j)にも機能します。また、自然対数の底(e)や円周率(pi)などの数学定数が事前に定義されています。
たとえばオイラーの等式
i*pi e = -1 |
を検証するためには、以下をタイプすると、これは計算の許容誤差(tolerance of the
calculation)とともに-1に評価されるでしょう。
octave:1> exp (i*pi) |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
ベクターとマトリクスは、数値解析における基本的な構成要素です。新たにマトリクスを作成して、それを変数に格納すれば、コマンドをタイプして後からそれを参照できます
octave:1> A = [ 1, 1, 2; 3, 5, 8; 13, 21, 34 ] |
Octaveは、列で整列されたマトリクスを表示して応答するでしょう。 Octave will respond by printing the matrix in neatly aligned columns.
Octaveは行の中の区切りにカンマ、またはスペースを使い、行ごとの区切りにはセミコロン、または改行を使用します。コマンドの最後にセミコロンを入力した場合、Octaveはコマンドの結果をプリントしません。たとえば、
octave:2> B = rand (3, 2); |
これは、それぞれの要素が0から1の間の乱数であるような、3行2列のマトリクスを作成します。
変数の値を表示するには、プロンプトで、単に変数名をタイプします。たとえばBに格納されたマトリクスの値を表示するには、以下のコマンドをタイプします
octave:3> B |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveには、行列演算を行なうための、便利な演算子があります。たとえばマトリクスAにスカラー値を乗ずるには、以下のコマンドを試してみてください
octave:4> 2 * A |
2つの行列AとBの内積は、以下のコマンドをタイプします
octave:5> A * B |
行列の積
transpose (A) * A,
を得るには、以下のコマンドをタイプします
octave:6> A' * A |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
数値解析において、線形方程式系(systems of linear
equations)は至るところに現れます。一連の線形方程式Ax = bを解くには、左除算演算子(left division
operator) ‘\’を使います:
x = A \ b |
これは、概念的には以下と等価です
inv (a) * b,
しかし、左除算演算子を使うことにより、逆行列を直接計算するのを避けることができます。
係数行列(coefficient matrix)が正則(singular)な場合、Octaveは警告をプリントして、最小ノルム解(minimum norm solution)を計算します。
化学から簡単な例を1つ。バランスのとれた化学反応式(balanced chemical equations)を得たいとします。水素と酸素の燃焼による水の生成を考えてみましょう。
H2 + O2 --> H2O |
この化学反応式は正確ではありません。質量保存の法則により、各分子の数は反応式の左辺と右辺でバランスが取れている必要があります。反応を通じて水素と酸素について個別に方程式を記述すると、以下のようになります:
x1*H2 + x2*O2 --> H2O H: 2*x1 + 0*x2 --> 2 O: 0*x1 + 2*x2 --> 1 |
Octaveでは、3つのステップだけでこれを解くことができます。
octave:1> A = [ 2, 0; 0, 2 ]; octave:2> b = [ 2; 1 ]; octave:3> x = A \ b |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveには、以下の形式をもち
dx -- = f (x, t) dt |
初期条件が以下であるような非線形方程式を解くビルトイン関数があります
x(t = t0) = x0 |
このような形式の関数をOctaveで積分するには、最初にその関数の定義を与えなければなりません
f(x,t).
これは簡単です。コマンドライン上で関数のボディを直接入力していけばよいのです。たとえば、以下のコマンドは、ある非線形微分方程式の着目する変数ペアにたいする右辺の関数を定義しています。関数を入力する間、Octaveは異なるプロンプトで応答することに注意してください。これは入力が完了するまでOctaveが待機していることを示します。
octave:1> function xdot = f (x, t) > > r = 0.25; > k = 1.4; > a = 1.5; > b = 0.16; > c = 0.9; > d = 0.8; > > xdot(1) = r*x(1)*(1 - x(1)/k) - a*x(1)*x(2)/(1 + b*x(1)); > xdot(2) = c*a*x(1)*x(2)/(1 + b*x(1)) - d*x(2); > > endfunction |
次に初期条件を与えます
octave:2> x0 = [1; 2]; |
そして出力時間を列ベクトルとしてセットします(1番目の出力時間は上記で与えた初期条件に対応することに注意してください)
octave:3> t = linspace (0, 50, 200)'; |
微分方程式の組を積分するのは簡単です:
octave:4> x = lsode ("f", x0, t);
|
関数lsodeは、「A. C. Hindmarsh, ODEPACK, a Systematized Collection
of ODE Solvers, in: Scientific Computing, R. S. Stepleman et al. (Eds.),
North-Holland, Amsterdam, 1983」の55ページから64ページで説明されている、"Livermore Solver for
Ordinary Differential Equation"を使用しています。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
前の例の解をグラフィカルに表示するには、以下のコマンドを使用します
octave:1> plot (t, x) |
グラフィカルユーザーインターフェイスを使用している場合、Octaveはプロットを表示するための別ウィンドウを自動的に作成するでしょう。
1度スクリーンに表示されたプロットを保存するには、printコマンドを使用します。たとえば、
print -deps foo.eps |
Encapsulated PostScriptフォーマットで描画された現在のプロットを含む、‘foo.eps’というファイルを作成します。また、以下のコマンド
help print |
は、printにたいする他のオプションの説明と、出力ファイルフォーマットの追加リストを提供します。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveプロンプトでは、Emacsスタイル、またはviスタイルを使用した、以前のコマンドの再呼び出し、編集、再実行が可能です。デフォルトのキーバインディングは、Emacsスタイルのコマンドを使用します。たとえば、前のコマンドを再び呼び出すには、Control-p(略記するとC-p)を押します。これを行なうことにより、入力した以前の行に戻ることができます。他にも、C-nで入力の次の行、C-bでカーソルをその行の後方へ移動、C-fでカーソルをその行の前方へ移動などができます。
コマンドライン編集の能力に関する完全な説明は、このマニュアルのsee section Command Line Editingで提供されています。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveには豊富なヘルプ機能があります。Octaveプロンプトから、同じドキュメントのプリント形式が利用できます。これはドキュメントの各形式が、同じ入力ファイルから作成されているからです。
望ましいヘルプを得るには、まず使いたいコマンドの名前を知る必要があります。この関数の名前が明確でない場合もあります。そのようなときは、help
--listとタイプするのがよい出発点です。これはすべての演算子、キーワード、ビルトイン関数、Octaveのカレントセッションで利用できるロード可能な関数をすべて表示します。代替としては、lookfor関数を使ってドキュメントを検索する方法もあります。この関数は、Commands for Getting Helpで説明されています。
使いたい関数の名前が解ったら、単にhelpの引数にその関数の名前を含めることで、さらなるヘルプを入手できます。たとえば、
help plot |
これはplot関数のヘルプテキストを表示します。
Octaveは、1つのスクリーンに収まらないような長い出力を、lessやmore風のページャーを通じて送ります。<RET>をタイプすると1行、<SPC>で1ページ進み、<q>でページャーを抜けます。
Octave内ででプリントされたマニュアルの完全なテキストを読むことができるOctaveのヘルプ機能の一部は、通常はInfoと呼ばれる別のプログラムを使用します。Infoを呼び出すと、Octaveマニュアル全体を含んだメニュー駆動型のプログラムが起動されます。Infoの使用に関するヘルプは、このマニュアルのsee section Commands for Getting Helpで提供されています。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
このセクションでは、このマニュアルで使われている表記規約について説明します。あなたはこのセクションを飛ばして、あとで参照したいと思うかもしれません。
| 1.3.1 Fonts | ||
| 1.3.2 Evaluation Notation | ||
| 1.3.3 Printing Notation | ||
| 1.3.4 Error Messages | ||
| 1.3.5 Format of Descriptions |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveコードの例は、svd
(a)のようなフォントまたは形式で表します。変数や関数の引数の名前を示す場合は、first-numberのようなフォントまたは形式で表します。シェルプロンプト上でタイプするコマンドは、‘octave
--no-init-file’のようなフォントまたは形式で表します。Octaveプロンプト上でタイプするコマンドは、foo --bar
--bazのようなフォントまたは形式で表す場合があります。キーボード上の特定のキーは、<ANY>のようなフォントまたは形式で表します。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
このマニュアル内の例では、あなたが評価した式の結果は、‘⇒’で示されます。たとえば、
sqrt (2)
⇒ 1.4142
|
あなたはこれを、“sqrt (2)は1.4142に評価された”と読み替えることができます。
式によりリターンされるマトリクス値は、以下のように表示される場合があります
[1, 2; 3, 4] == [1, 3; 2, 4]
⇒ [ 1, 0; 0, 1 ]
|
また、以下のように表示される場合もあります
eye (3)
⇒ 1 0 0
0 1 0
0 0 1
|
これは結果の構造を明確にするためです。
1つの式を説明するのに、同じ結果を生成する別の式を示すのが助けになる場合もあります。式の完全な等価は、‘≡’で表します。たとえば:
rot90 ([1, 2; 3, 4], -1) ≡ rot90 ([1, 2; 3, 4], 3) ≡ rot90 ([1, 2; 3, 4], 7) |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
このマニュアルの例の多くは、評価されたときにテキストをプリントします。このマニュアルでは、例の結果としてプリントされるものを、‘-|’で表します。式の評価によりリターンされた値(次の例の1)は、続けて別の行に‘⇒’で表します。
printf ("foo %s\n", "bar")
-| foo bar
⇒ 1
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
エラーをシグナルする例もいくつかあります。これらは通常、端末上にエラーメッセージを表示します。エラーメッセージは行頭のerror:で表します。
fieldnames ([1, 2; 3, 4]) error: fieldnames: Invalid input argument |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
このマニュアルでは、関数とコマンドは統一されたフォーマットで説明されています。説明の最初の行には、そのアイテムの名前と、もしあれば引数が含まれます。 行の先頭はカテゴリー—function、commandなど—が表示されます。 後続の行が説明で、例を含む場合もあります。
| 1.3.5.1 A Sample Function Description | ||
| 1.3.5.2 A Sample Command Description |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
関数の説明では、説明される関数の名前が最初に表示されます。同じ行にパラメーターのリストが続きます。パラメーターに使用された名前は、説明の本文でも使用されます。
以下は、架空の関数fooの説明です:
関数fooはyからxを減じたのち、残りの引数を結果に加算します。yが与えられない場合、デフォルトとして数値19が使用されます。
foo (1, [3, 5], 3, 9)
⇒ [ 14, 16 ]
foo (5)
⇒ 14
|
より一般的には、
foo (w, x, y, …) ≡ x - w + y + … |
名前に型名(例: integerやmatrix)を含むパラメーターは、その型が期待されます。objectという名前のパラメーターは、任意の型です。他の種類の名前(例: new_file)をもつパラメーターについては、その関数の説明の中で個別に説明されます。いくつかのセクションでは、複数の関数で共通のパラメーターは、最初に説明されます。
Octave内の関数は、複数の異なる方法で定義されているかもしれません。関数のカテゴリー名には、その関数が定義された方法を示す他の名前が含まれる場合があります。これらの追加タグには以下が含まれます。
説明されている関数は、テキストファイルに格納されたOctaveコマンドにより定義されています。Function Filesを参照してください。
説明されている関数は、C++、C、またはFortranのような言語で記述されており、コンパイル済みOctaveバイナリーの一部です。
説明されている関数は、C++、C、またはFortranのような言語で記述されています。ユーザー定義関数の動的リンクをサポートするシステムでは、Octaveの実行中に、必要なときだけ自動的にリンクされます。
説明されている関数は、マトリクスおよびベクター引数の要素ごとに作用します。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
コマンドの説明は、単語‘Function’が‘Command’置き換わることを除き、関数の説明と同じフォーマットです。コマンドとは、引数をカッコで括らずに呼び出される関数です。たとえば、以下はOctaveのcdコマンドの説明です。
カレント作業ディレクトリーをdirに変更します。たとえばcd ~/octaveは、カレント作業ディレクトリーを‘~/octave’に変更します。そのディレクトリーが存在しない場合、エラーメッセージをプリントし、作業ディレクトリーは変更されません。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
このチャプターでは、Octaveの基本的な機能についていくつか説明します。それらの機能にはOctaveセッションの開始、コマンドプロンプトでのヘルプの入手、コマンド行の編集、シェルプロンプトからコマンドとして実行可能なOctaveプログラムの記述が含まれます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveは通常、引数を指定せずに‘octave’プログラムを実行することにより、対話的に使用されます。一度開始すると、exitを指示するまで、Octaveは端末からコマンドを読み取ります。
コマンドラインにファイル名を指定することもできます。この場合、Octaveはその名前のファイルからコマンドを読み込んで実行し、それが終了したらexitします。
さらに次のセクションで説明するコマンドラインオプションにより、Octaveをどのように開始するか、制御することができます。Octave自身が、利用できるオプションを知らせることができます。‘octave --help’(短い形式は‘octave -h’)とタイプすると、利用できるすべてのオプションと、使い方の簡略が表示されます。
| 2.1.1 Command Line Options | ||
| 2.1.2 Startup Files |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
以下は、Octaveに指定できるコマンドラインオプションの、完全なリストです。
--built-in-docstrings-file filenameOctaveのビルトイン関数のドキュメント文字列を含むファイルの名前を指定します。この値は通常は正しいので、異常な状況において指定する必要なときだけ指定するべきです。
--debug-dパーサーのデバッグモードに入ります。このオプションを使うことにより、Octaveが読み込んだコマンドについて、Octaveパーサーが大量の情報をプリントするようになるので、おそらくパーサーのデバッグを実際に試みるときだけ有用でしょう。
--debug-jitJITコンパイラーのデバッグとトレースを有効にします。
--doc-cache-file filename使用するドキュメントキャッシュファイルを指定します。コマンドラインで指定されたfilenameの値は、環境変数OCTAVE_DOC_CACHE_FILEの値をオーバーライドします。しかし、doc_cache_fileを使用する、システムまたはユーザーのスタートアップファイルのコマンドを除きます。
--echo-commands-xコマンドが実行されると、そのコマンドをエコーします。
--eval codecodeを評価して、‘--persist’が共に指定されていなければ、評価の終了と共にexitします。
--exec-path path実行するプログラムうぃ検索するパスを指定します。コマンドラインで指定されたpathの値は、環境変数OCTAVE_EXEC_PATHの値をオーバーライドします。しかし、ビルトイン変数EXEC_PATHをセットする、システムまたはユーザーのスタートアップファイルのコマンドを除きます。
--force-gui起動時にグラフィカルユーザーインターフェイス(FUI)を強制します。
--help-h-?短いヘルプメッセージをプリントして、exitします。
--image-path pathイメージを検索するパスのheadにパスを追加します。コマンドラインで指定されたpathの値は、環境変数OCTAVE_IMAGE_PATHの値をオーバーライドします。しかし、ビルトイン変数IMAGE_PATHをセットする、システムまたはユーザーのスタートアップファイルのコマンドを除きます。
--info-file filename使用するinfoファイルの名前を指定します。コマンドラインでfilenameに指定された値は、環境変数OCTAVE_INFO_FILEの値をオーバーライドします。しかし、info_file関数を使用する、システムまたはユーザーのスタートアップファイルのコマンドを除きます。
--info-program program使用するinfoプログラムの名前を指定します。コマンドラインで指定されたprogramの値は、環境変数OCTAVE_INFO_PROGRAMの値をオーバーライドします。しかし、info_program関数を使用する、システムまたはユーザーのスタートアップファイルのコマンドを除きます。
--interactive-i対話的な動作を強制します。これはリモートシェルコマンドやEmacsのシェルバッファーを通じてOctaveを実行するとき便利かもしれません。
--jit-compilerJITコンパイラーのループ高速化を有効にします。
--line-editingコマンドライン編集に、readlineの使用を強制します。
--no-guiグラフィカルユーザーインターフェイス(GUI)を無効にして、かわりにコマンドラインインターフェイス(CLI)を使用します。
--no-history-Hコマンドラインのヒストリーの記録を無効にします。
--no-init-file初期化ファイル‘~/.octaverc’および‘.octaverc’を読み込みません。
--no-init-pathデフォルトの場所を含めるための、関数ファイル用の検索パス初期化を行いません。
--no-line-editingコマンドライン編集を無効にします。
--no-site-fileサイト単位の初期化ファイル‘octaverc’を読み込みません。
--no-window-system-Wグラフィックスを含めてウィンドウシステムの使用を無効にします。これは端末だけに制限された環境を強制します。
--norc-fスタートアップ時に、システムまたはユーザーの初期化ファイルを読み込みません。これは、‘--no-init-file’と‘--no-site-file’の両方のオプションを使用することと同じです。
--path path-p path関数ファイルの検索パスにheadにパスを追加します。コマンドラインで指定されたpathの値は、環境変数OCTAVE_PATHの値をオーバーライドします。しかしシステムまたはユーザーのスタートアップファイルで、path関数のいずれかを通じてセットされた内部のloadパスは除きます。
--persist‘--eval’またはコマンドラインで指定された名前のファイルを読み込んだ後に、インタラクティブモードに移ります。
--silent--quiet-q起動時に通常のグリーティングメッセージとバージョンメッセージをプリントしません。
--texi-macros-file filenamemakeinfoにより使用されるTexinfoマクロを含むファイルの名前を指定します。
--traditional--braindeadMATLABとの互換のために、ユーザープリファレンスとして、以下の値を初期値としてセットします。
PS1 = ">> " PS2 = "" allow_noninteger_range_as_index = true beep_on_error = true confirm_recursive_rmdir = false crash_dumps_octave_core = false save_default_options = "-mat-binary" do_braindead_shortcircuit_evaluation = true fixed_point_format = true history_timestamp_format_string = "%%-- %D %I:%M %p --%%" page_screen_output = false print_empty_dimensions = false |
そして、以下の警告を無効にします。
Octave:abbreviated-property-match Octave:fopen-file-in-path Octave:function-name-clash Octave:load-file-in-path |
これはOctave:matlab-incompatible警告を有効にしないことに注意してください。Octaveでは機能するが、MATLABでは機能しないコードの記述にたいして警告してほしいときは、この警告を有効にしたいと思うでしょう(詳細はwarning、およびwarning_idsを参照してください)。
--verbose-V詳細な出力に切り替えます。
--version-vプログラムのバージョンナンバーをプリントしてexitします。
filefileのコマンドを実行します。‘--persist’が指定されていない場合は、実行が終了した後にexitします。
Octaveには、引数の数やすべてのオプションなど、コマンドラインの情報についてリターンする関数がいくつかあります。
Octaveに渡されたコマンドライン引数をリターンします。たとえば以下のようなコマンドを使用してOctaveを呼び出した場合、
octave --no-line-editing --silent |
argvは、要素が‘--no-line-editing’と‘--silent’であるようなセル配列をリターンするでしょう。
実行可能なOctaveスクリプトを記述した場合、argvはそのスクリプトに渡された引数のリストをリターンします。実行可能なOctaveスクリプトを記述する例は、Executable Octave Programsを参照してください。
program_invocation_nameからリターンされた値(フルパス)の、最後の成分(ファイル名)をリターンします。
See also: program_invocation_name.
Octaveを実行するためにシェルプロンプトにタイプされた名前をリターンします。
コマンドラインからスクリプトを実行した場合(例: octave
foo.m)、あるいは実行可能なOctaveスクリプトを使用した場合、プログラム名はしのスクリプトの名前にセットされます。実行可能なOctaveスクリプトを作成する例は、Executable Octave Programsを参照してください。
See also: program_name.
以下は、これらの関数を使用して、Octaveを呼び出したコマンドラインを再現する例です
printf ("%s", program_name ());
arg_list = argv ();
for i = 1:nargin
printf (" %s", arg_list{i});
endfor
printf ("\n");
|
セル配列からオブジェクトを取得する方法についての説明はIndexing Cell Arrays、変数narginについての情報はDefining Functionsを参照してください。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveが開始されるとき、Octaveは以下のリストのファイルから、実行するコマンドを探します。これらのファイルには、関数定義を含む、任意の有効なOctaveコマンドが含まれるでしょう。
octave-home/share/octave/site/m/startup/octavercoctave-homeはOctaveがインストールされたディレクトリーです(デフォルトは‘/usr/local’))。このファイルは、デフォルトのOctave環境にたいする変更を、そのサイトのすべてのユーザー、インストールされたOctaveのすべてのバージョンにたいして全体的に適用するために提供されています。このファイルへの変更は、そのサイトのOctaveユーザーすべてに影響を与えるため、注意を払うべきです。デフォルトファイルは、環境変数yによりオーバーライドされるかもしれません。
octave-home/share/octave/version/m/startup/octavercoctave-homeはOctaveがインストールされたディレクトリー(デフォルトは‘/usr/local’)、versionはOctaveのバージョンナンバーです。このファイルは、特定のバージョンのOctaveを使用するすべてのユーザーにたいして、デフォルトのOctave環境への変更を全体的に適用するために提供されています。そのサイトで対象となるバージョンのOctaveを使用するすべてのユーザーに影響を与えるため、このファイルの変更には注意が払われるべきです。デフォルトファイルは環境変数OCTAVE_VERSION_INITFILEにより、オーバーライドされるかもしれません。
~/.octavercこのファイルは、デフォルトOctave環境にたいして個人的に変更を行なうために使用されます。
.octavercこのファイルは、特定のプロジェクトのデフォルトOctave環境にたいして変更を行なうために使用されます。Octaveは、‘~/.octaverc’を読み込んだ後に、カレントディレクトリーからこのファイルを検索します。‘~/.octaverc’ファイル内でのcdコマンドの使用は、Octaveが‘.octaverc’を検索するディレクトリーに影響を与えます。
ホームディレクトリーでOctaveを開始した場合、ファイル‘~/.octaverc’のコマンドは一度だけ実行されます。
‘--silent’オプションを指定せずに‘--verbose’オプションでOctaveを呼び出した場合、スタートアップファイルが読み込まれるたびに、メッセージが表示されます。
どのようなカスタマイズが可能で、どのカスタマイズが有効になっているかを決定するには、dump_prefs関数が便利です。
後からOctaveでパースできる形式で、現在のすべてのユーザープリファレンス変数をダンプします。fidはfopenからリターンされたファイルディスクリプターです。fileが省略された場合、リストはstdoutにプリントされます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
現在のOctaveセッションをexitします。オプションの整数値statusが与えられた場合、Octaveのexit statusとして、その値をオペレーティングシステムに渡します。デフォルト値は0です。
Octaveをexitするときに呼び出される関数を登録します。たとえば、
function last_words ()
disp ("Bye bye");
endfunction
atexit ("last_words");
|
これはOctaveをexitするとき、メッセージ"Bye bye"をプリントします。
追加の引数flagは、Octaveをexitするときに呼び出される関数のリストに、fcnを登録、または登録を取り消します。flagがtrueの場合、その関数は登録され、flagの場合は、その関数の登録が取り消されます。たとえば、上述の関数last_wordsを登録した後に
atexit ("last_words", false);
|
これはリストから関数を取り除くので、Octaveがexitするときlast_wordsは呼び出されません。
atexitはリストから最初の関数だけを取り除くことに注意してください。atexitによりリストに関数が複数ある場合は、同じように複数回取り除かなければなりません。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
このマニュアルのテキスト全体は、Octaveプロンプトからdocコマンドを通じて利用できます。さらにユーザーが独自に記述した関数や変数のドキュメントも、helpコマンドを通じて利用できます。このセクションでは、マニュアルやユーザーが定義した関数や変数のドキュメント文字列を読むために使用するコマンドを説明します。作成した関数のドキュメント記述については、Function Filesを参照してください。
--list.nameにたいするヘルプテキストを表示します。たとえば、コマンドhelp
helpはhelpコマンドを説明する短いメッセージをプリントします。
単一の引数--listが与えられた場合は、演算子、キーワード、ビルトイン関数、および現在のOctaveセッションで利用できるロード可能な関数を、すべてリストします。
単一も引数.が与えられた場合は、現在のOctaveセッションで利用できる、すべての演算子をリストします。
引数を指定せずに呼び出した場合、helpはコマンドラインからヘルプにアクセスする手順を表示します。
helpコマンドにより、コマンドの区切り文字に使用されるカンマとセミコロンを除いた、演算子の情報を得ることができます。それらについてのヘルプを得るには、help commaやhelp semicolonとタイプしなければなりません。
GNU Infoブラウザを使用して、プリントされたマニュアルのオンラインバージョンから、関数function_nameのドキュメントを直接表示します。引数を指定せずに呼び出した場合、マニュアルの冒頭から表示されます。
たとえば、コマンドdoc randはマニュアルのオンラインバージョンのrandノードからGNU Infoブラウザを開始します。
GNU Infoブラウザが実行されると、コマンドC-hを使用して、使い方のヘルプを得ることができます。
See also: help.
現在の関数検索パスで見つかったすべての関数の中から、文字列strを検索します。デフォルトでは、lookforは見つかった関数それぞれのヘルプ文字列の最初のセンテンスからstrを検索します。引数"-all"が与えられた場合は、それぞれの関数のヘルプテキスト全体から検索します。検索はすべて大文字小文字を区別しません。
出力引数を指定せずに呼び出された場合、lookforはマッチした関数のリストを端末にプリントします。指定された場合、出力引数funcおよびhelpstringには、マッチした関数とその関数のヘルプ文字列の最初のセンテンスが定義されます。
最初のセンテンスを正しく認識するlookforの能力は、その関数のヘルプのフォーマットに依存します。Octaveの中心的な関数はすべて正しくフォーマットされていますが、外部パッケージとユーザー定義関数について同様に保証することはできません。したがって、Octaveの一部ではない、関連のある関数を見つけるために、"-all"引数の使用が必要になるかもしれません。
Octaveのカレントリリースで何が新しくなったか確認するには、news関数を使用します。
OctaveまたはインストールされたパッケージのカレントNEWSファイルを表示します。
引数を指定せずに呼び出した場合は、OctaveのNEWSファイルを表示します。パッケージ名packageが与えられた場合は、そのパッケージのカレントNEWSファイルを表示します。
GNU Octaveコミュニティーに連絡を取るための情報を表示します。
Octaveを複製、および配布するための条件を説明します。
以下の関数は、ドキュメントを表示するために使用されるプログラムys,ドキュメントを探す場所を変更するために使用されます。
Octaveのinfoファイルの名前を指定する内部変数にたいして問い合わせ、またはセットをします。デフォルト値は‘octave-home/info/octave.info’です。octave-homeはOctaveをインストールしたルートディレクトリーです。デフォルト値は、環境変数OCTAVE_INFO_FILE、またはコマンドライン引数‘--info-file
FNAME’によりオーバーライドされるかもしれません。
関数内から"local"と共に呼び出された場合、変数にたいする変更は、その関数と関数が呼び出すサブルーチンにたいしてローカルになります。その関数をexitするとき、変数の元の値がリストアされます。
See also: info_program, doc, help, makeinfo_program.
実行するinfoプログラムの名前を指定する内部変数の問い合わせ、またはセットを行います。デフォルト値は‘octave-home/libexec/octave/version/exec/arch/info’で、octave-homeはOctaveをインストールしたルートディレクトリー、versionはOctaveのバージョンナンバー、そしてarchはシステムタイプ(たとえばi686-pc-linux-gnu)です。デフォルト値は、環境変数OCTAVE_INFO_PROGRAM、またはコマンドライン引数‘--info-program
NAME’でオーバーライドされるかもしれません。
関数の中から"local"オプションと共に呼び出された場合、変数への変更ははその関数および関数のサブルーチンにたいしてローカルになります。その関数をexitするときに、変数の元の値がリストアされます。
See also: info_file, doc, help, makeinfo_program.
Texinfoのマークアップコマンドを含むヘルプテキストをフォーマットするためにOctaveが実行するプログラム名を指定する内部変数にたいして、問い合わせまたはセットを行います。デフォルト値はmakeinfoです。
関数の中から"local"オプションと共に呼び出された場合、その変数にたいする変更は、その関数および関数のサブルーチンにたいしてローカルになります。関数をexitするときに、変数の元の値がリストアされます。
See also: texi_macros_file, info_file, info_program, doc, help.
ドキュメント文字列がmakeinfoに渡される前に、文字列の前に追加されるTexinfoマクロを含むファイルの名前を指定する内部変数にたいして、問い合わせまたはセットを行います。デフォルト値は‘octave-home/share/octave/version/etc/macros.texi’です。ここで、octave-homeはOctaveをインストールしたルートディレクトリー、versionはOctaveのバージョンナンバーです。デフォルト値は、環境変数OCTAVE_TEXI_MACROS_FILE、またはコマンドライン引数‘--texi-macros-file
FNAME’により、オーバーライドされるかもしれません。
関数の中から"local"オプションと共に呼び出された場合、変数への変更は、その関数または関数のサブルーチンにたいしてローカルになります。関数をexitするときに、変数の元の値がリストアされます。
See also: makeinfo_program.
Octaveのドキュメントキャッシュファイルの名前を指定する内部変数にたいして、問い合わせ、またはセットを行います。キャッシュファイルは、lookforコマンドはパフォーマンスを大幅に改善します。デフォルト値は‘octave-home/share/octave/version/etc/doc-cache’です。ここで、octave-homeはOctaveをインストールしたルートディレクトリー、versionはOctaveのバージョンナンバーです。デフォルト値は、環境変数OCTAVE_DOC_CACHE_FILE、またはコマンドライン引数‘--doc-cache-file
FNAME’によりオーバーライドされるかもしれません。
関数の中から"local"オプションと共に呼び出された場合、変数への変更は、その関数または関数のサブルーチンにたいしてローカルになります。関数をexitするとき、変数の元の値がリストアされます。
See also: doc_cache_create, lookfor, info_program, doc, help, makeinfo_program.
Octaveのビルトイン関数のdocstringを含むファイルの名前を指定する内部変数にたいして、問い合わせまたはセットを行います。デフォルト値は‘octave-home/share/octave/version/etc/built-in-docstrings’です。ここで、octave-homeはOctaveをインストールしたルートディレクトリー、versionはOctaveのバージョンナンバーです。デフォルト値は、環境変数OCTAVE_BUILT_IN_DOCSTRINGS_FILE、またはコマンドライン引数‘--built-in-docstrings-file
FNAME’によりオーバーライドされるかもしれません。
注意: この変数はOctave自身の初期化時だけ使用されます。Octaveセッション実行中に変更しても、Octaveに影響しません。
helpコマンドの出力とビルトイン関数の使い方メッセージのの最後に、Octaveが付加的なヘルプ情報を追加するかどうかと、を制御する内部変数にたいして、問い合わせまたはセットを行います。
関数の中から"local"オプションと共に呼び出された場合、変数の変更は、その関数または関数のサブルーチンにたいしてローカルになります。関数をexitするときに、元の変数の値がリストアされます。
以下の関数は、ドキュメントを生成するために、主にOctaveにより内部的に使用されます。これらの関数は、ユーザーにとって便利なときがあるかもしれないので、ここに完全なドキュメントを示します。
与えられたディレクトリー内のすべての関数にたいするドキュメントキャッシュを生成します。
directory内のすべての関数にたいするドキュメントキャッシュを生成します。生成されたキャッシュは、ファイルout_fileに保存されます。このキャッシュは、lookforのスピードアップのために使用されます。
ディレクトリーが与えられない(または空のマトリクスが与えられた)場合は、ビルトイン演算子などにたいするキャッシュが生成されます。
See also: doc_cache_file, lookfor, path.
関数nameのrawヘルプテキストをリターンします。
textにrawヘルプテキスト、formatのフォーマットがリターンされます。フォーマットは文字列で、"texinfo"、"html"、"plain
text"のうちの1つです。
ファイルfnameのrawヘルプテキストをリターンします。
textにrawヘルプテキスト、formatのフォーマットがリターンされます。フォーマットは文字列で、"texinfo"、"html"、"plain
text"のうちの1つです。
関数のヘルプテキストの最初のセンテンスをリターンします。
最初のセンテンスとは、関数定義の後ろから、最初のピリオド(".")、または連続する改行("\n\n")までのテキストです。テキストは最大長max_len(デフォルトは80)に切り詰められます。
オプションの出力引数statusには、makeinfoかr報告されたステータスがリターンされます。要求される出力引数が1つで、statusが非0の場合は警告が表示されます。
例として、この関数のヘルプテキストの最初のセンテンスは、以下のようになります
get_first_help_sentence ("get_first_help_sentence")
-| ans = Return the first sentence of a function's help text.
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveは、豊富なコマンドライン編集とヒストリー機能を提供するために、GNU Readlineライブラリーを使用しています。このマニュアルでは、もっとも一般的な機能についてだけ説明します。さらに、すべての編集コマンドは、ユーザーにより自由に別のキーストロークのバインドできます。このマニュアルでは、Emacsのデフォルトのキーバインディングを変更していない前提で説明します。Readlineのカスタマイズと、完全な機能については、GNU Readlineのマニュアルを参照してください。
印字可能文字(文字、数字、シンボルなど)の挿入は、単にその文字をタイプするだけです。Octaveはカーソル位置に文字を挿入して、カーソルを前方に進めます。
コマンドライン編集関数の操作の多くは、コントロール文字を使用します。たとえば文字Control-aは、カーソルをその行の先頭に移動します。C-aのタイプは、<CTRL>を押したまま、<a>を押します。以降のセクションでは、Control-aのようなコントロール文字は、C-aと表記します。
メタ文字を使用するコマンドライン編集関数もあります。M-uをタイプするには、<META>キーを押したまま、<u>を押します。キーボードによっては、<META>が<ALT>とラベルされていたり、<WINDOWS>とラベルされていることさえあります。端末に<META>がない場合でも、ESCで始まる2文字シーケンスを使ってメタ文字を入力できます。この場合M-uを入力するには、<ESC>の次に<u>をタイプします。実際のMetaキーがある端末でも、ESC文字シーケンスは利用できます。以降のセクションでは、Meta-uのようなメタ文字は、M-uのように表記します。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
以下のコマンドで、カーソルを動かすことができます。
1文字後退します。
1文字前進します。
カーソルの左の文字を削除します。
カーソルの下の文字を削除します。
カーソルの下の文字を削除します。
1単語前方に移動します。
1単語後方に移動します。
行の先頭に移動します。
行の末尾に移動します。
スクリーンをクリアーして、カレント行をスクリーンのトップに再印字します。
最後の操作をアンドゥします。すべてをアンドゥして空の行まで戻ることができます。
その行へのすべての変更をアンドゥします。これは最初に戻るまで充分な回数だけ‘undo’コマンドをタイプするのと同様です。
上記のテーブルでは、入力行で編集を行うのに必要となる、もっとも基本的な利用できるキーストロークを説明しています。ほとんどの端末では、C-fやC-bで前方または後方へ移動するのに、左矢印キーと右矢印キーも利用できます。
C-fは1文字前方、M-fは1単語前方へ移動する点に注目してください。コントロールによるキーストロークは文字単位の処理、メタによるキーストロークは単語単位の処理という、緩い慣習があります。
関数clcにとり、実行中のOctaveプログラム内のスクリーンをクリアーできます。
端末スクリーンをクリアーして、カーソルを左上隅に移動します。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
テキストをキルするとは、行からテキストを削除しますが、後でそれを使用する(通常はヤンクにより行に戻す)ために、それを保存するという意味です。コマンドの説明で、そのコマンドがテキストを‘キル’する、と記述されているときは、後から違う(または同じ)場所に戻せることが保証されます。
以下はテキストをキルするコマンドのリストです。
現在のカーソル位置から行末までのテキストをキルします。
カーソルから現在の単語の末尾まで、カーソルが単語と単語の間にある場合は次の単語の末尾までをキルします。
カーソルから現在の単語の先頭まで、カーソルが単語と単語の間にある場合は前の単語の先頭までをキルします。
カーソルから前の空白までをキルします。単語境界が違うので、M-<DEL>とは異なります。
以下は、その行にテキストをyankで戻す方法です。ヤンクとは、kキルバッファーからもっとも最近キルされたテキストをコピーするという意味です。
そのバッファーのカーソル位置に、もっとも最近キルされたテキストをヤンクして戻します。
キルリンクをローテートして、新たなトップをヤンクします。直前のコマンドがC-yまたはM-yのときだけ、これを行なうことができます。
キルコマンドを使うと、そのテキストはキルリング(kill-ring)に保存されます。任意の回数の連続したキルコマンドは、キルされたすべてのテキストを1つにまとめるので、それをヤンクで戻すときは、一度にまとめてヤンクできます。キルリングは特定の行に限定されたものではありません。以前にタイプしたラインでキルしたテキストは、後で他の行をタイプしているときに、ヤンクで戻すことができます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
以降のコマンドは、他の場合では特別な意味をもつ文字(例: <TAB>、C-qなど)を入力したり、タイプミスをすばやく訂正するために使用できます。
次にタイプする文字そのものを、行に追加します。これは、C-qのような文字を挿入する方法の一例です。
Insert a tab character.
カーソルのある文字の前方にカーソルの前の文字をドラッグするとともに、カーソルを進めます。カーソルが行の末尾にある場合は、カーソルの前の2文字を入れ換えます。
同様に、カーソルの前方の単語をカーソルの後方へドラッグして、カーソルの後方にあった単語の前方にカーソルを移動します。
現在の単語(または次の単語からの)の末尾までを大文字にして、その単語の末尾にカーソルを移動します。
現在の単語(または次の単語からの)の末尾までを小文字にして、その単語の末尾にカーソルを移動します。
カーソルの前方(カーソルが単語と単語の間にある場合は次の単語の先頭)を大文字にして、その単語の末尾にカーソルを移動します。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
以降のコマンドにより、コマンドや変数の名前をOctaveに補完させることができます。
カーソルの前のテキストにたいして補完を試みます。Octaveはコマンドと変数の名前を補完することができます。
カーソルの前のテキストにたいして、可能な補完をリストします。
コマンドラインの成功した補完に追加する文字のための内部変数にたいして、問い合わせまたはセットを行います。デフォルト値は"
"(スペース1つ)です。
関数の中から"local"オプションと共に呼び出された場合、変数の変更は、その関数または関数のサブルーチンにたいしてローカルになります。関数をexitするときに、元の変数の値がリストアされます。
与えられたhintにたいして、可能な補完を生成します。
この関数は、Octaveを制御したりユーザー入力を処理するEmacsのようなプログラムのために提供されています。この関数が呼び出されても、カレントコマンドナンバーはインクリメントされません。これはバグではなく仕様です。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveは通常、以前にタイプされたコマンドうぃ編集や再実行できるように、タイプしたコマンドを記録しています。Octaveをexitするとき、もっとも最近タイプされたコマンドから、変数history_sizeで指定された個数までのコマンドがファイルに保存されます。Octaveが開始されるとき、変数history_fileの名前のファイルから、コマンドの初期リストがロードされます。
以下は、ヒストリーリストを簡単に閲覧したり、検索するためのコマンドです。
カーソルの位置に関わらず、カレント行を受け入れます。その行が空でない場合は、その行をヒストリーに加えます。その行がヒストリー行だった場合は、ヒストリー行を元の状態にリストアします。
ヒストリーリストを‘上’に移動します。
ヒストリーリストを‘下’に移動します。
ヒストリーリストの最初の行に移動します。
入力ヒストリーの最後の行(あなたが入力している行です!)に移動します。
カレント行から後方検索を開始して、必要ならヒストリーを‘上’に移動します。これはインクリメンタル検索です。
カレント行から前方検索を開始して、必要ならヒストリーを‘下’に移動します。
多くの端末では、ヒストリーリストを移動するのに、C-pやC-nのかわりに上矢印キーと下矢印キーを使用できます。
ヒストリーリストを移動するコマンドに加えて、Octaveはヒストリーリストからコマンド群を閲覧、編集、再実行するために3つの関数を提供します。
引数を指定せずに呼び出すと、historyは実行されたコマンドのリストを表示します。有効なオプションは:
n-nヒストリーリストのもっとも最近のn行だけを表示します。
-cヒストリーリストをクリアーします。
-q表示されるヒストリーリストの番号を表示しません。これは、X Window Systemを使用してカットアンドペーストを行なうときに便利です。
-r fileファイルfileを読み込んで、その内容をカレントヒストリーリストに追加します。名前が省略された場合はデフォルトのヒストリーファイル(通常は‘~/.octave_hist’)を使用します。
-w fileカレントヒストリーを、ファイルfileに書き込みます。名前が省略された場合はデフォルトのヒストリーファイル(通常は‘~/.octave_hist’)を使用します。
たとえば、もっとも最近タイプされたコマンド5つを、行番号なしで表示するには、コマンドhistory -q 5を使用します。
出力引数が1つで呼び出された場合、ヒストリーはその引数のセル文字列として保存され、スクリーンに表示されません。
変数EDITORで指定された名前のエディターを使って、ヒストリーリストを編集します。
編集されるコマンドは、最初にテンポラリーファイルにコピーされます。エディターをexitするとき、Octaveはそのファイル内に残ったコマンドを実行します。関数を定義するとき、それを直接コマンドラインに入力するのではなく、edit_historyを使うほうが便利なときがあります。そのコマンドブロックは、エディターをexitするとすぐに実行されます。コマンドを実行したくないときは、エディターを抜けるときに、単にそのバッファーのすべての行を削除してください。
引数なしで呼び出された場合は、以前に実行されたコマンドを編集します。引数が1つの場合は、指定されたコマンドcmd_numberを編集します。引数が2つの場合は、firstとlastの間のコマンドを編集します。コマンド番号には、負の数も指定できます。この場合、-1はもっとも最近実行されたコマンドを参照します。以下のコマンドは等価で、どちらももっとも最近実行されたコマンドを編集します。
edit_history edit_history -1 |
範囲を使用する場合、最初のコマンドに最後のコマンドより大きい番号を指定すると、編集されるバッファーに配置される前に、コマンドリストを逆転します。
See also: run_history.
ヒストリーリストからコマンドを実行します。
引数なしで呼び出された場合は、以前に実行されたコマンドを実行します。引数が1つの場合は、指定されたコマンドcmd_numberを実行します。引数が2つの場合は、firstとlastの間のコマンドを実行します。コマンド番号には、負の数も指定できます。この場合、-1はもっとも最近実行されたコマンドを参照します。以下のコマンドは等価で、どちらももっとも最近実行されたコマンドを編集します。たとえば以下のコマンド
run_history
OR
run_history -1
|
はもっとも最近のコマンドを再実行します。また、
run_history 13 169 |
は13から169のコマンドを実行します。
最初のコマンドに最後のコマンドより大きい番号を指定すると、編集されるバッファーに配置される前に、コマンドリストを逆転します。たとえば:
disp (1) disp (2) run_history -1 -2 ⇒ 2 1 |
See also: edit_history.
Octaveでは、ヒストリーがいつ、どこで、どのように保存されたかの詳細もカスタマイズできます。
ヒストリーファイルに、コマンドがコマンドラインから入力されたかどうかを保存するか制御する内部変数にたいして、問い合わせまたはセットを行います。
関数内から"local"オプションと共に呼び出された場合、変数の変更はその関数および関数のサブルーチンにたいしてローカルになります。その関数をexitするとき、変数の元の値がリストアされます。
See also: history_control, history_file, history_size, history_timestamp_format_string.
コマンドがヒストリーリストに保存される方法を指定する内部変数にたいして、問い合わせまたはセットを行います。デフォルト値は空文字列ですが、環境変数OCTAVE_HISTCONTROLによりオーバーライドされるかもしれません。
history_controlの値は、コマンドをヒストリーリストに保存する方法を制御する、コロンで区切られた値です。値リストがignorespaceを含む場合、スペース文字で始まる行は、ヒストリーリストに保存されません。ignoredupsでは、以前のヒストリーにマッチする行はヒストリーに保存されません。値ignorebothは、ignorespaceとignoredupsの省略指定です。値erasedupsは、カレント行がヒストリーリストに保存される前に、ヒストリーリストからマッチするすべての行を削除します。上記のリスト以外の値はすべて無視されます。history_controlが空文字列の場合、すべてのコマンドはhistory_saveの値として、すべてヒストリーリストに保存されます。
See also: history_file, history_size, history_timestamp_format_string, history_save.
コマンドヒストリーを保存するのに使用するファイルの名前を指定する内部変数にたいして、問い合わせまたはセットを行います。デフォルト値は‘~/.octave_hist’ですが、環境変数OCTAVE_HISTFILEによりオーバーライドされるかもしれません。
See also: history_size, history_save, history_timestamp_format_string.
ヒストリーファイルに保存するエントリー数を指定する内部変数にたいして、問い合わせまたはセットを行います。デフォルト値は1000ですが、環境変数OCTAVE_HISTSIZEによりオーバーライドされるかもしれません。
See also: history_file, history_timestamp_format_string, history_save.
Octaveをexitするときにヒストリーファイルに書き込まれるコマンドラインにたいするフォーマット文字列を指定する内部変数にたいして、問い合わせまたはセットを行います。このフォーマット文字列はstrftimeに渡されます。デフォルト値は
"# Octave VERSION, %a %b %d %H:%M:%S %Y %Z <USER@HOST>" |
関数内から"local"オプションと共に呼び出された場合、変数の変更はその関数または関数のサブルーチンにたいしてローカルになります。関数をexitするときに、変数の元の値がリストアされます。
See also: strftime, history_file, history_size, history_save.
デフォルトのテキストエディターを指定する内部変数にたいして、問い合わせまたはセットを行います。
デフォルト値はOctave開始時に環境変数EDITORから取得されます。環境変数が初期化されない場合、EDITORは"emacs"にセットされます。
関数の中から"local"オプションと共に呼び出された場合、変数の変更は、その関数または関数のサブルーチンにたいしてローカルになります。関数をexitするときに、元の変数の値がリストアされます。
See also: edit, edit_history.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
readlineOctaveはコマンドライン変数およびヒストリー機能のために、GNU Readlineライブラリーを使用しています。Readlineはとてもフレキシブルで、コマンドの設定ファイルを通じてカスタマイズできます(正確なコマンド構文についてはGNU Readlineライブラリーを参照してください)。デフォルトの設定ファイルは通常、‘~/.inputrc’です。
OctaveはReadlineを初期化するためのコマンドを提供しており、それによりコマンドラインの挙動を変更できます。
readline初期化ファイルfileを読み込みます。fileが省略された場合には、デフォルトの初期化ファイル(通常は‘~/.inputrc’)を読み込みます。
詳細は(readline)Readline Init File section ‘Readline Init File’ in GNU Readline Libraryを参照してください。
See also: readline_re_read_init_file.
最後に読み込んだreadline初期化ファイルを再読込します。詳細は (readline)Readline Init File section ‘Readline Init File’ in GNU Readline Libraryを参照してください。
See also: readline_read_init_file.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
以降の変数による、コマンドラインプロンプトの外観をカスタマイズできます。Octaveでは、バックスラッシュでエスケープされたいくつかの特別な文字を挿入することにより、プロンプトをカスタマイズできます。それらの文字は以下のようにデコードされます:
時刻。
日付。
改行と復帰と等価なものをプリントすることにより、新たな行を開始します。
プログラムの名前(通常は単に‘octave’)です。
カレントワーキングディレクトリー。
カレントワーキングディレクトリーのbasename。
カレントユーザーのユーザー名。
最初の‘.’までのhostname。
hostname。
Octave起動後からカウントした、そのコマンドのコマンド番号。
そのコマンドのヒストリー番号。これはOctave開始時からのヒストリーリスト内のコマンド数なので、‘\#’とは異なります。
実行UIDが0のときは‘#’、それ以外は‘$’。
文字コードが8進nnnの文字。
バックスラッシュ。
一次プロンプト(primary prompt)文字列にたいして、問い合わせまたはセットを行います。インタラクティブに実行された場合は、コマンドを読み取る準備ができたときに、Octaveは一次プロンプトを表示します。
一次プロンプト文字列のデフォルト値は"octave:#> "です。これを変更するには、以下のようなコマンドを使用します。
PS1 ("\\u@\\H> ")
|
これは、ホスト‘kremvax.kgb.su’にログインしているユーザー‘boris’のプロンプトを、‘boris@kremvax> ’にします。ダブルクォートされた文字列内にバックスラッシュを入力するには、バックスラッシュが2つ必要なことに注意してください。Stringsを参照してください。
端末がサポートしていれば、ANSIエスケープシーケンスも使用できます。これはプロンプトにカラーを使いたいとき便利かもしれません。たとえば、
PS1 ("\\[\\033[01;31m\\]\\s:\\#> \\[\\033[0m\\]")
|
これはデフォルトのOctaveプロンプトのカラーを赤にします。
関数の中から"local"オプションと共に呼び出された場合、変数の変更はその関数または関数のサブルーチンにたいしてローカルになります。関数をexitするときに、変数の元の値がリストアされます。
二次プロンプト文字列にたいして、問い合わせまたはセットを行います。二次プロンプトは、Octaveがコマンドを完成させるために、追加入力を待っているときにプリントされます。たとえば、複数行に分かれたforループをタイプしているとき、Octaveは最初の行以降の各行の先頭に二次プロンプトをプリントするでしょう。二次プロンプト文字列のデフォルト値は、">
"です。
関数の中から"local"オプションと共に呼び出された場合、変数の変更はその関数または関数のサブルーチンにたいしてローカルになります。関数をexitするときに、元の変数の値がリストアされます。
コマンドのエコーが有効なときに、生成された出力のプレフィクスに使用する文字列の、問い合わせまたはセットを行います。デフォルト値は"+
"です。コマンドのエコーについての説明は、Diary and Echo Commandsを参照してください。
関数の中から"local"オプションと共に呼び出された場合、変数の変更はその関数または関数のサブルーチンにたいしてローカルになります。関数をexitするときに、変数の元の値がリストアされます。
See also: echo, echo_executing_commands, PS1, PS2.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveのダイアリー機能により、インタラクティブなセッションのすべて、または一部のログを維持できます。これは、タイプされた入力と、Octaveが生成した出力を、別のファイルに記録することにより行なわれます。
すべてのコマンドのリストおよびそれらが生成した出力を、まさに端末に表示されたよyに混在して記録します。
有効なオプションは:
カレントワーキングディレクトリーの‘diary’と呼ばれるファイルへ、セッションの記録を開始します。
ダイアリーファイルへのセッションの記録を停止します。
filenameという名前のファイルに、セッションを記録します。
引数を指定しない場合、カレントダイアリーの状態うぃ切り替えます。
See also: history.
関数やスクリプトが評価されるときに、それらの中のコマンドを確認できると便利な場合があります。これは、ある種の問題をデバッグするとき、特に助けになるでしょう。
コマンドが評価されるときに、それらのコマンドを表示するかどうかを制御します。有効なオプションは:
onスクリプトファイル内でコマンドが実行されるとき、エコーを有効にします。
offスクリプトファイル内でコマンドが実行されるとき、エコーを無効にします。
on allスクリプトファイルおよび関数内でコマンドが実行されるとき、エコーを有効にします。
off allスクリプトファイルおよび関数内でコマンドが実行されるとき、エコーを無効にします。
引数を指定しない場合、echoはエコー状態を切り替えます。
エコー状態を制御する内部変数にたいして、問い合わせまたはセットを行います。値は以下の値の和になるでしょう:
スクリプトファイルから読み込んだコマンドをエコーします。
関数のコマンドをエコーします。
コマンドラインから読み込んだコマンドをエコーします。
一度に2つ以上の状態がアクティブになり得ます。たとえば、値3は、コマンドecho on allと等価です。
echo_executing_commandsの値は、echoコマンドまたはコマンドラインオプション‘--echo-commands’によりセットされるかもしれません。
関数の中から"local"オプションと共に呼び出された場合、変数の変更は、その関数または関数のサブルーチンにたいしてローカルになります。関数をexitするときに、元の変数の値がリストアされます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveは無効なプログラムにたいして、2つの種類のエラーをリポートします。
パースエラーは、Octaveがタイプされたものを理解できなかった場合に発生します。たとえば、キーワードのスペルミスをした場合、
octave:13> function y = f (x) y = x***2; endfunction |
Octaveは即座に次のようなメッセージを返すでしょう:
parse error:
syntax error
>>> function y = f (x) y = x***2; endfunction
^
|
多くのパースエラーにたいして、Octaveは入力行で理解できなかった箇所をマークするのに、キャレット(‘^’)を使用します。上記のケースでは、べき乗(**)にたいするキーワードにスペルミスがあるので、Octaveはエラーメッセージを生成しました。キャレットは3つ目の‘*’にエラーをマークしました。なぜなら、その箇所まではコードは正しく読み取れていたけれど、最後の‘*’が理解できなかったからです。
他のクラスのエラーメッセージは、評価時に発生します。これらのエラーは、ランタイムエラーまたは, 評価エラーと呼ばれることもあります。これは、それらのエラーが、プログラムが実行(run)あるいは評価(evaluate)されるときに発生するからです。たとえば、前の関数定義のミスを訂正したあとで、以下をタイプしたとします
octave:13> f () |
Octaveは以下のように応答するでしょう
error: `x' undefined near line 1 column 24 error: called from: error: f at line 1, column 22 |
このエラーメッセージにはいくつかのパートがあります。そして、それらはエラーのあるソースを見つける助けとなる情報を多く含んでいます。このメッセージは、最内のエラー箇所から生成され、それを囲む式と関数呼び出しのバックトレースを提供します。
上記の例の最初の行は、何らかの関数または式の、行1、列24の近くで、名前‘x’の未定義な変数が見つかったことを示しています。関数内で発生したエラーにたいしては、行はその関数定義を含むファイルの先頭から数えた行のことです。関数の外側で発生したエラーにたいしては、行番号は入力行番号であり、これは通常一次プロンプト文字列に表示されています。
エラーメッセージの2行目と3行目は、このエラーが関数fの中で発生したことを示しています。もし関数fがさらに他の関数、たとえばgから呼び出されていた場合には、エラーリストにはさらに以下のような1行が加わるでしょう:
error: g at line 1, column 17 |
これらの関数呼び出しのリストは、エラーが発生するまでにそのプログラムがとったパスのトレースと、プログラムを再試行する前にエラーを訂正するのを、とても簡単にします。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
一度Octaveを習得したら、‘#!’スクリプトメカニズムを使ってOctaveによる自己完結型スクリプトを記述したいと思うかもしれません。これはGNUシステム、および多くのUnixシステム(1)で行なうことができます。
Octave自己完結型スクリプトは、Octave言語で記述されたプログラムに関する知識を要さずに、ユーザーが呼び出せるプログラムを記述したいときに便利です。Octaveスクリプトは、データファイルのバッチプロセッシングにも使用されます。一度アルゴリズムが開発され、Octaveのインタラクティブ環境でテストされれば、それを実行可能スクリプトにコミットして、データファイルに何度も使用できます。
実行可能Octaveスクリプトの些細な例として、あなたは以下の行を含む‘hello’という例の名前のファイルを作るかもしれません:
#! octave-interpreter-name -qf
# a sample Octave program
printf ("Hello, world!\n");
|
(octave-interpreter-nameはOctaveバイナリーのフルパスで置き換えてください)。スクリプトはファイルの先頭に‘#!’があるときだけ機能することに注意してください。(Unixシステムではchmodで)ファイルを実行可能にした後は、以下のようにシェル上で単にタイプできます:
hello |
システムはあなたがタイプしたものを以下のようにアレンジして、Octaveを実行します:
octave hello |
‘#!’で始まる行は、実行されるインタープリターのファイル名へのフルパスと、そのインタープリターに渡す初期化のためのオプションのコマンドライン引数です。するとオペレーティングシステムは与えられた引数と、実行されるプログラムの完全な引数リストにより、インタープリターを実行します。リストの最初の引数は、実行可能なOctaveのフルパスファイル名です。引数リストの残りはOctaveへのオプション、データファイル、またはその両方です。‘-qf’オプションは通常、スタンドアローンなOctaveプログラム内での、通常のスタートアップメッセージのプリントを抑止して、特定のユーザーの‘~/.octaverc’の内容に依存した異なる挙動から守ります。Invoking Octave from the Command Lineを参照してください。
‘#!’の後ろの文字数に制限のあるオペレーティングシステムがいくつかあることに注意してください。また、‘#!’の行内の引数のパースは、さまざまなシェルやシステムにより異なります。これらの多くは、すべての引数を1つの文字列にまとめて、インタープリターに1つの引数として渡します。この場合、以下のスクリプト:
#! octave-interpreter-name -q -f # comment |
は、コマンドラインで以下のようにタイプするのと等価です:
octave "-q -f # comment" |
そして、これはエラーになるでしょう。残念ながら、コマンドラインから呼び出されたのか、それとも‘#!’スクリプトから呼び出されたかを、Octaveが判断するのは不可能です。したがって、‘#!’メカニズムを使用するときは、いくつかの配慮が必要です。
Octaveが実行可能スクリプトから起動された場合、ビルトイン関数argvはスクリプトの‘#!’行でOctaveインタープリターに渡された引数ではなく、実行可能Octaveスクリプトに渡されたコマンドライン引数を含むセル配列をリターンします。たとえば、以下のプログラムは‘-qf’ではなく、スクリプトを実行するために使用されたコマンドライン引数を再現します。
#! /bin/octave -qf
printf ("%s", program_name ());
arg_list = argv ();
for i = 1:nargin
printf (" %s", arg_list{i});
endfor
printf ("\n");
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
コメントとは、人間の読み手のためにプログラム中に含まれるテキストのことで、このテキストはプログラムの実行パートではありません。コメントにより、そのプログラムが何を行なうか、どのように機能するか説明することができます。ほとんどすべてのプログラミング言語にはコメントにたいする規約があります。なぜならプログラムは通常、コメントがなければ理解するのが困難だからです。
| 2.7.1 Single Line Comments | ||
| 2.7.2 Block Comments | ||
| 2.7.3 Comments and the Help System |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave言語では、コメントはシャープ記号‘#’、あるいはパーセント記号‘%’のどちらかで始まり、その行の末尾までがコメントになります。シャープ記号またはパーセント記号に続く任意のテキストは、Octaveインタープリターには無視され、実行されません。以下の例では、行全体のコメントと、行の一部を使用したコメントが使用されています。
function countdown
# Count down for main rocket engines
disp (3);
disp (2);
disp (1);
disp ("Blast Off!"); # Rocket leaves pad
endfunction
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
マッチする‘#{’と‘#}’、または‘%{’と‘%}’で囲むことにより、コードブロック全体をコメント化することができます。たとえば、
function quick_countdown
# Count down for main rocket engines
disp (3);
#{
disp (2);
disp (1);
#}
disp ("Blast Off!"); # Rocket leaves pad
endfunction
|
これは、"disp (2);"と"disp
(1);"を実行しないことにより、'3'から"Blast Off"へのとても素早いカウントダウンを生成します。
ブロックコメントマーカーは、正しくパースされるために、その行で(空白文字以外の)単独の文字として記述しなければなりません。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
helpコマンド(Commands for Getting Help参照)は、関数の最初のコメントブロックを見つけて、それらをドキュメント文字列としてリターンします。これはヘルプを取得するために使用する同じコマンドが、ユーザー定義関数を正しくフォーマットできることを意味します。たとえば、以下の関数fを定義してみます
function xdot = f (x, t) # usage: f (x, t) # # This function defines the right-hand # side functions for a set of nonlinear # differential equations. r = 0.25; … endfunction |
すると、コマンドhelp fは以下の出力を生成します
usage: f (x, t) This function defines the right-hand side functions for a set of nonlinear differential equations. |
キーボード入力して使い捨てするプログラムにコメント行を挿入することはできますが、これは通常とても有用とは言えません。なぜならコメントの目的は、後で他の人がプログラムを理解する助けとなることだからです。
helpパーサーは、初期ヘルプテキストとして、1行コメント(Single Line Comments参照)だけを正しく認識します。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveのすべてのバージョンにはいくつかのビルトインデータ型が含まれます。それらには、real(実数)およびcomplex(複素数)にたいするスカラー(scalar)とマトリクス(matrix)、文字列(character string)、データ構造型(data structure type)、そしてすべてのデータ型を含むことができる配列(array)が含まれます。
少しC++コードを記述すれば、新しく特別なデータ型を定義することもできます。Octave実行中に新しいデータ型をダイナミック(動的)にロードできるシステムもいくつかあり、その場合はOctaveすべてをリコンパイルせずに、新しいデータ型を単に追加できます。Octaveのダイナミックリンク能力についての情報は、External Code Interfaceを参照してください。User-defined Data Typesでは、Octaveに新しいデータ型を定義するために、何を行わなければならないか説明しています。
式exprの型を、文字列でリターンします。exprが省略された場合は、現在インストールされているデータ型すべてを含む文字列のセル配列をリターンします。
| 3.1 Built-in Data Types | ||
| 3.2 User-defined Data Types | ||
| 3.3 Object Sizes |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
標準のビルトインデータ型は、real(実数)およびcomplex(複素数)のスカラー(scalar)およびマトリクス(matrix)、range(レンジ、範囲)、文字列(character string)、データ構造型(data structure type)、セル配列(cell array)です。将来のバージョンで、さらにビルトインデータ型が追加されるかもしれません。現在ビルトイン型として提供されていない、特別なデータ型が必要な場合は、あなたが独自にユーザー定義データ型を記述して、それをOctaveの将来リリースのディストリビューションのために寄贈されることをお勧めします。
以下の関数を使用して、変数のデータ型の判定と変更ができます。
オブジェクトobjのクラスをリターン、または構造sのフィールド、およびnameフィールド(文字列)がidのクラスを作成します。追加の引数は、新しいクラスがどのクラスから継承されたかを示す親クラスの名前のリストです。
objがクラスclassnameならばtrueをリターンします。
classnameは、以下のクラスカテゴリーの1つかもしれません:
"float"float(浮動小数点)の値は、クラス"double"および"single"を包括します。
"integer"integer(整数)の値は、クラス(u)int8、(u)int16、(u)int32、(u)int64を包括します。
"numeric"numericの値は、浮動小数点値と整数値を包括します。
valをデータ型typeに変換します。
See also: int8, uint8, int16, uint16, int32, uint32, int64, uint64, double.
メモリー内でxのデータをnumericクラスclassのデータとして解釈し、結果を新たな配列yでリターンします。xとclassはどちらも、ビルトインnumericクラスの1つでなければなりません。
"logical" "char" "int8" "int16" "int32" "int64" "uint8" "uint16" "uint32" "uint64" "double" "single" "double complex" "single complex" |
最後の2つは、classのために予約されています。これらは、complex値の結果が要求されていることを示します。complex配列は、連続するreal値として、メモリー内に格納されます。integer型のサイズは、それらのビット数で与えられます。logicalとcharはどちらも1バイト幅です。しかしこれはC++により保証されていません。システムがIEEE準拠の場合、singleとdoubleは、4バイトおよび8バイト幅です。"logical"は、classに指定できません。入力が行ベクターならリターン値は行ベクターで、それ以外は列ベクターです。xのビット長がclassのビット長の倍数でない場合は、エラーが発生します。
リトルエンディアン機でtypecastを使用する例は
x = uint16 ([1, 65535]); typecast (x, "uint8") ⇒ [ 1, 0, 255, 255] |
値のバイト順を入れ替えて、リトルエンディアンからビッグエンディアン、またはその逆の変換をします。
swapbytes (uint16 (1:4)) ⇒ [ 256 512 768 1024] |
配列xをnumericクラスclassのrawビット配列として解釈した結果を、新たな配列yでリターンします。classはビルトインnumericクラスのうちの1つでなければなりません。
"char" "int8" "int16" "int32" "int64" "uint8" "uint16" "uint32" "uint64" "double" "single" |
xの要素の個数は、classのビット長の倍数である必要があります。もしそうでない場合には、余分なビットは無視されます。ビット順は、x(1)がビット0、x(2)がビット1、のように、昇順になっています。結果は、xが行ベクターなら行ベクター、それ以外は列ベクターになります。
xのrawビットパターンに対応する配列yをリターンします。xはビルトインnumericクラスの1つに属していなければなりません:
"char" "int8" "int16" "int32" "int64" "uint8" "uint16" "uint32" "uint64" "double" "single" |
結果はxが行ベクターなら行ベクター、それ以外は列ベクターです。
| 3.1.1 Numeric Objects | ||
| 3.1.2 Missing Data | ||
| 3.1.3 String Objects | ||
| 3.1.4 Data Structure Objects | ||
| 3.1.5 Cell Array Objects |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveのビルトインnumericオブジェクトには、real、complex、integerのスカラーとマトリクスが含まれます。すべてのビルトイン浮動小数点numericデータは、現在のところ倍精度浮動小数点数として格納されます。IEEE浮動小数点フォーマットを使用するシステムでは、およそ
2.2251e-308から1.7977e+308
までの範囲の値が格納でき、相対精度はおよそ
2.2204e-16です。
正確な値はそれぞれ、変数realmin、realmax、epsで得ることができます。
マトリクスオブジェクトは任意のサイズをとることができ、動的に変形やサイズ変更ができます。種々の強力なインデクス機能を使用して、特定の行や列、サブマトリクスが簡単に抽出できます。Index Expressionsを参照してください。
詳細は、Numeric Data Typesを参照してください。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveでは、NA(“Not
Available”の略)を使用して、欠損データを明示的に表すことができます。欠損データが表されるのは、データが浮動小数点数として表されるときだけです。この場合、欠損データはNaNの特別なケースとして表されます。
すべての要素が、欠損値を示すために使用される特別な定数と等しいようなスカラー、マトリクス、N次元配列をリターンします。
NAとNAの比較は常にノットイコール(NA !=
NA)になることに注意してください。NA値を見つける場合には、isna関数を使用してください。
引数を指定しないで呼び出された場合は、値‘NA’のスカラーをリターンします。1つの引数で呼び出された場合は、指定された次元の正方マトリクスをリターンします。2つ以上のスカラー引数で呼び出された場合、最初の2つは行数と列数を指定し、残りは追加のマトリクス次元を指定します。オプション引数classは、リターン型を指定し、"double"か"single"です。
See also: isna.
xの要素がNA値(欠損値)のところはtrue、異なるところはfalseであるようなlogical配列をリターンします。たとえば:
isna ([13, Inf, NA, NaN])
⇒ [ 0, 0, 1, 0 ]
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveでの文字列は、ダブルクォーテーション、またはシングルクォーテーションで囲まれた文字シーケンスで構成されます。内部的には現在のところ、Octaveは文字列を文字のマトリクスとして格納します。マトリクスオブジェクトに機能するインデクス操作のすべては、文字列にたいしても機能します。
詳細は、Stringsを参照してください。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveにデータ構造型は、異なる型の関連するオブジェクトを組織化する助けになります。現在の実装では、インデクスが文字列に限定された連想配列を使用しますが、構文はCスタイルの構造体に類似しています。
詳細は、Structuresを参照してください。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveのセル配列(Cell Array)は、異なるデータ型を任意個もつことができる、汎用配列です。
詳細は、Cell Arraysを参照してください。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
わたしはいつかOctaveのユーザー定義データ型の管理にたいする管理メカニズムについての完全なドキュメントを含めることで、このセクションを拡張したいと思っています。ここにその機能がドキュメントされるまで、あなたがそれを行なうためには、Octaveの‘src’ディレクトリーにある‘ov.h’、‘ops.h’、および関連するファイルのコードを読む必要があるでしょう。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
以降の関数により、変数や式のサイズを判定できます。これらの関数は、すべてのオブジェクトにたいして定義されています。これらは操作に意味がない場合は、-1をリターンします。たとえば、Octaveのデータ構造型は行や列を持たないので、rowsやcolumnsの関数は、構造型の引数にたいしては、-1をリターンします。
aの次元数をリターンします。任意の配列にたいし、結果は2以上になります。後続のシングルトン次元(singleton dimension: 1と等しい次元)はカウントされません。
ndims (ones (4, 1, 2, 1))
⇒ 3
|
See also: size.
aの列数をリターンします。
See also: rows, size, length, numel, isscalar, isvector, ismatrix.
aの行数をリターンします。
See also: columns, size, length, numel, isscalar, isvector, ismatrix.
オブジェクトa内の要素数をリターンします。オプションで、もしidx1、idx2、…が与えられた場合は、インデクス操作の結果
a(idx1, idx2, …) |
の要素数をリターンします。インデクスは数値である必要はないことに注意してください。たとえば、
a = 1; b = ones (2, 3); numel (a, b) |
こてはbでインデクスをつける方法で、6をリターンします。
この手法は、オブジェクトがcsリスト(カンマ区切りリスト)のインデクス操作のlvalue(左辺値)として現れたときにも使用されます(例:
object{…}またはobject(…).field)。
See also: size.
オブジェクトaの長さをリターンします。
lengthは、空のオブジェクトにたいしては0、スカラーにたいしては1、ベクターにたいしては要素数です。マトリクスオブジェクトについては、行数または列数の大きい方がlengthになります(この奇妙な定義は、MATLABとの互換のために使用されます)。
aの行数と列数をリターンします。
入力引数が1つで、出力引数が1つの場合、結果は行ベクターでリターンされます。出力引数が複数の場合、行数が1つ目、列数が2つ目の出力引数、などとなります。たとえば:
size ([1, 2; 3, 4; 5, 6])
⇒ [ 3, 2 ]
[nr, nc] = size ([1, 2; 3, 4; 5, 6])
⇒ nr = 3
⇒ nc = 2
|
2つ目の引数が与えられた場合、sizeは対応する次元のサイズをリターンします。たとえば、
size ([1, 2; 3, 4; 5, 6], 2)
⇒ 2
|
これは与えられたマトリクスの列数をリターンします。
aが空のマトリクス(マトリクスの次元のうち1つが0)の場合はtrue、それ以外はfalseをリターンします。
xがマトリクス、文字列、シングルクォートされた文字列で、それらが特別な値nullの場合は、trueをリターンします。右辺にこのような値があるインデクス割り当てでは、配列の要素が削除されます。以下のようなケースと区別するため、ユーザー定義クラスのインデクス割り当てのオーバーロードでは、isemptyのかわりにこの関数を使用するべきです:
A(I) = []これはIが空でない場合は、要素を削除します。
X = []; A(I) = Xこれは、Iが空でない場合は、エラーになります。
valのサイズをバイトでリターンします。
See also: whos.
すべての引数の次元が一致する場合は、trueをリターンします。後続のシングルトン次元は無視されます。引数が1つ、または指定されない場合、size_equalはtrueをリターンします。
xからシングルトン次元を削除して、その結果をリターンします。MATLABとの互換のため、すべてのオブジェクトは少なくとも2つの次元をもち、行ベクターは変更されません。
See also: reshape.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
numeric定数はスカラー、ベクター、マトリクスであるかもしれず、さらにそれらはcomplex値を含むかもしれません。
もっともシンプルなnumeric定数の形式はスカラーです。スカラーは単独の数であり、整数、少数、科学表記(指数表記)の数値、複素数を含むことができます。Octave内ではデフォルトではnumeric定数は倍精度浮動小数点数で表されることに注意してください(complex定数は倍精度浮動小数点数のペアーとして格納されます)。しかし、Integer Data Typesで説明するように、real整数(実数型整数)で表すこともできます。以下にreal値のnumeric定数の例をいくつか示します。これらはすべて同じ値をもちます:
105 1.05e+2 1050e-1 |
complex定数を指定する場合は、以下の形式で式を記述できます
3 + 4i 3.0 + 4.0i 0.3e1 + 40e-1i |
これらはすべて等価です。この例の文字‘i’は純虚数定数(pure imaginary constant)を意味しており、
sqrt (-1)と定義されます。
Octaveがcomplex定数の虚部(imaginary part)を認識するためには、数字と‘i’の間にスペースがあってはなりません。スペースが存在する場合、Octaveは以下のようなエラーメッセージをプリントします:
octave:13> 3 + 4 i
parse error:
syntax error
>>> 3 + 4 i
^
|
上記の例で‘i’が出現する箇所には‘j’、‘I’、‘J’を使うこともできます。これら4つの形式は、すべて等価です。
xを倍精度型に変換します。
See also: single.
realの引数から、complexの結果をリターンします。realの引数がxの1つの場合、結果はcomplexのx
+ 0iになります。realの引数が2つの場合、結果はcomplexのre + imになります。a
+ i*bのような式よりも、complexのほうが便利な場合もあります。たとえば:
complex ([1, 2], [3, 4]) ⇒ [ 1 + 3i 2 + 4i ] |
| 4.1 Matrices | ||
| 4.2 Ranges | ||
| 4.3 Single Precision Data Types | ||
| 4.4 Integer Data Types | ||
| 4.5 Bit Manipulations | ||
| 4.6 Logical Values | ||
| 4.7 Promotion and Demotion of Data Types | ||
| 4.8 Predicates for Numeric Objects |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveで値のマトリクスを定義するのは、簡単です。マトリクスのサイズは自動的に決定されるので、次元を明示する必要はありません。以下の式
a = [1, 2; 3, 4] |
の結果は、以下のマトリクスになります
/ \
| 1 2 |
a = | |
| 3 4 |
\ /
|
さまざまなピースをまとめたときに、すべての次元が意味をなすなら、任意の式をマトリクスの要素にできます。たとえば、上記のマトリクスが与えられた場合、以下の式
[ a, a ] |
は、以下のマトリクスを生成します
ans = 1 2 1 2 3 4 3 4 |
しかし、以下の式
[ a, 1 ] |
は、エラーを生成します
error: number of rows must match (1 != 2) near line 13, column 6 |
(このエラーは、この式が13行目の行頭から入力された場合です)。
マトリクス式を区切る角カッコの中では、スペース文字と改行文字を要素と行区切りに変換すべきか、あるいは単に無視すべきかを判断するために、Octaveは周囲のコンテキストを調べます。そのため、以下のような式
a = [ 1 2
3 4 ]
|
は機能するでしょう。しかし混乱の種はまだ残っています。たとえば、以下の式
[ 1 - 1 ] |
では‘-’は2項演算子とみなされ、その結果はスカラー0になります。しかし以下の式
[ 1 -1 ] |
では‘-’は単項演算子とみなされ、結果はベクター[ 1, -1 ]になります。同様に、以下の式
[ sin (pi) ] |
は以下のよyにパースされて
[ sin, (pi) ] |
これはsin関数が引数なしで呼び出されたとみなされて、エラーになります。エラーを回避するためには、sinと開きカッコの間のスペースを取り除くか、式をカッコで括らなければなりません:
[ (sin (pi)) ] |
転置演算子(transpose
operator)と文字列の区切りに使用される、空白文字ど囲まれたシングルクォート文字(‘'’も混乱を招きます。a =
1が与えられた場合、以下の式
[ 1 a' ] |
では、シングルクォート文字は転置演算子とみなされて、結果はベクター[ 1, 1 ]になります。しかし以下の式
[ 1 a ' ] |
はエラーメッセージを生成します
parse error:
syntax error
>>> [ 1 a ' ]
^
|
なぜなら、これをエラーにしないと、以下のような有効な式をパースするときトラブルになるからです
[ a 'foo' ] |
明確にするためには、マトリクスの要素と行の区切りには常に、カンマとセミコロンを使用するのがおそらく最善でしょう。
マトリクスの要素の最大数は、Octaveのコンパイル時に決定されていて固定です。可能な数は、関数sizemaxで問い合わせることができます。マシン上で利用できるメモリーなど、他の要因により、マトリクスの最大要素数の制限は、いくぶん小さくなるかもしれないことに注意してください。
配列のサイズにたいして許される最大の値をリターンします。Octaveが64-bit
indexingでコンパイルされている場合はint64クラスの最大値、それ以外はint32クラスの最大値になります。配列の最大サイズは、intmaxでリポートされる関連するクラスに許される最大値より、少しだけ小さくなります。
See also: intmax.
マトリクス、または値がマトリクスである変数の名前をタイプすると、Octaveは行と列を整列してプリントします。そのマトリクスの行がスクリーンに収まらないほど大きい場合、Octaveはマトリクスを分割して、どの列が表示されているかを示すヘッダーを各セクションの前に表示します。出力フォーマットを制御するために、以下の変数を使用できます。
numeric出力フィールドの最大幅を指定する内部変数にたいして、問い合わせまたはセットを行います。
関数の中から"local"オプションと共に呼び出された場合、変数の変更はその関数または関数のサブルーチンにたいしてローカルになります。関数をexitするとき、変数の元の値がリストアされます。
See also: format, fixed_point_format, output_precision.
numeric出力にたいして表示する最小の有効数字を指定する内部変数にたいして、問い合わせまたはセットを行います。
関数の中から"local"オプションと共に呼び出された場合、変数の変更はその関数または関数のサブルーチンにたいしてローカルになります。関数をexitするとき、変数の元の値がリストアされます。
See also: format, fixed_point_format, output_max_field_width.
output_precisionとoutput_max_field_widthに異なる値を使用することにより、幅広い出力スタイルを実現できます。format関数をセットして、妥当な組み合わせをセットできます。Basic Input and Outputを参照してください。
端末ウィンドウに表示するときにマトリクスの行を分割するかどうかを制御する内部変数にたいして、問い合わせまたはセットを行います。行を分割する場合、Octaveはマトリクスを小さい断片のシリーズとして表示します。断片はそれぞれ、端末の制限幅に適合するよう分割され、各行セットにはラベルが付されるので、現在どの列が表示されているか簡単に識別できます。たとえば:
octave:13> rand (2,10) ans = Columns 1 through 6: 0.75883 0.93290 0.40064 0.43818 0.94958 0.16467 0.75697 0.51942 0.40031 0.61784 0.92309 0.40201 Columns 7 through 10: 0.90174 0.11854 0.72313 0.73326 0.44672 0.94303 0.56564 0.82150 |
関数の中から"local"オプションと共に呼び出された場合、変数の変更はその関数または関数のサブルーチンにたいしてローカルになります。関数をexitするとき、変数の元の値がリストアされます。
See also: format.
値が非常に大きくなったとき、または小さくなったとき、Octaveは自動的に科学的表記に切り替えます。これはマトリクス内のすべての値にたいして、数桁の有効数字を確認できることを保証します。マトリクス内のすべての値を固定小数点フォーマットで確認したい場合は、ビルトイン変数fixed_point_formatを非0値にセットすることができます。しかしこれを行なうことにより、容易に誤解釈され得る出力を生成するため、推奨されません。
Octaveがマトリクスの値をプリントするためにスケール化されたフォーマットを使用するかどうかを制御する内部変数にたいして、問い合わせまたはセットを行います。
スケール化されたフォーマットは、出力の最初の行にスケール因子をプリントします。スケール因子はマトリクスの最大要素を、整数部1桁で記述できるように選択されます。たとえば:
logspace (1, 7, 5)' ans = 1.0e+07 * 0.00000 0.00003 0.00100 0.03162 1.00000 |
最初の値は実際は1なのに、0のように見えることに注目してください。混乱を招く可能性があるため、fixed_point_formatの有効化には注意が必要です。
関数の中から"local"オプションと共に呼び出された場合、変数の変更はその関数または関数のサブルーチンにたいしてローカルになります。関数をexitするとき、変数の元の値がリストアされます。
See also: format, output_max_field_width, output_precision.
| 4.1.1 Empty Matrices |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
マトリクスの1つ、または両方の次元が0の場合があり、このような空マトリクスへの操作は、Carl de Boor in
An Empty Exercise, SIGNUM, Volume 25, pages 2-6, 1990 and C. N. Nett
and W. M. Haddad, in A System-Theoretic Appropriate Realization of
the Empty Matrix Concept, IEEE Transactions on Automatic Control, Volume
38, Number 5, May 1993で説明されています。
簡単にいうと、スカラーsm行n列のマトリクスM(mxn)、m行n列の空マトリクス(1つまたは両方の次元が0)[](mxn)が与えられたとき、以下が成り立ちます:
s * [](mxn) = [](mxn) * s = [](mxn)
[](mxn) + [](mxn) = [](mxn)
[](0xm) * M(mxn) = [](0xn)
M(mxn) * [](nx0) = [](mx0)
[](mx0) * [](0xn) = 0(mxn)
|
デフォルトでは、空マトリクスの次元は、空マトリクスのシンボル‘[]’と共にプリントされます。ビルトイン変数print_empty_dimensionsが、この振る舞いを制御します。
空マトリクスの次元を空マトリクスのシンボル‘[]’と共にプリントするかどうかを制御する内部変数にたいして、問い合わせまたはセットを行います。たとえば、以下の式
zeros (3, 0) |
は、以下のようにプリントするでしょう
ans = [](3x0) |
関数の中から"local"オプションと共に呼び出された場合、変数の変更はその関数または関数のサブルーチンにたいしてローカルになります。関数をexitするとき、変数の元の値がリストアされます。
See also: format.
空マトリクスは、マトリクスから行や列を簡単に削除する方法として、割り当てステートメント内でも使用されます。Assignment Expressionsを参照してください。
Octaveがマトリクス式をパースする場合な要素がすべて定数かどうか、要素のリストを調べます。そして、すべて定数ならば、そのリストを1つのマトリクス定数に置き換えます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
レンジ(range: 範囲)は、等差の要素からなる行ベクターを記述する便利な方法です。レンジ式は、そのレンジ内の最初の値、オプションとして要素間の増分値、そしてそのレンジの要素の上限となる最大値により定義されます。これらのベース、増分、リミットはコロン(‘:’文字)で区切られ、任意の算術式や関数呼び出しを含むことができます。増分が省略された場合、増分は1とみなされます。たとえば、以下のレンジ
1 : 5 |
は、値‘[ 1, 2, 3, 4, 5 ]’を定義します。また、以下のレンジ
1 : 3 : 5 |
は、値‘[ 1, 4 ]’を定義します。
レンジ定数で行ベクターを指定しても、Octaveは変換する必要がなければ、レンジ定数をベクターに変換しません。これにより、‘1 : 10000’のような定数を記述しても、ストレージを消費(通常の32ビットワークステーション上では8000バイト)せずにすみます。
レンジをベクターに変換する必要が生じる例としては、それらがベクター(例: 角カッコの内側)と共に記述されるときです。たとえば、
x = 0 : 0.1 : 1; |
これは、xをrange型として定義し、式のために24バイトのメモリーを占めます
y = [ 0 : 0.1 : 1]; |
これは、yをmatrix型として定義し、88バイトのメモリーを占めます。
レンジの上限(増分が負の場合は下限)は常に値セットに含まれるとは限らないこと、そして浮動小数点で定義されたレンジは、レンジ内の値の計算にOctaveが浮動小数演算を使用するので、驚くような結果を生成するかもしれないことに注意してください。レンジの終端を含めることが重要で、なおかつ要素数が既知の場合は、linspace関数(Special Utility Matrices参照)をかわりに使用してください。
レンジにたいするスカラーの加算と減算(またはスカラーからレンジの減算)、および乗算の場合、Octaveじゃレンジの展開を試みずに、展開しても安全だと判断できるまで、結果をレンジのまま保留します。たとえば、
a = 2*(1:1e7) - 1; |
これは‘1:2:2e7-1’と同じ結果を生成しますが、1000万個の要素をもつベクターが生成されるわけではありません。
コロン表記で‘1:0:1’のように増分に0を使用するのは、レンジ要素の個数を決定するとき0除算が発生するために、許されていません。しかし、増分0(例: すべての要素が同じ)のレンジは有用(よく特にインデクス操作において)なので、Octaveではビルトイン関数onesを使用してそれらを構築できます。レンジは行にベクターでなければならないので、‘ones (1, 10)’はレンジを構成しますが、‘ones (10, 1)’はレンジを構成しません。
Octaveがレンジ式をパースするとき、その式の要素がすべて定数かどうか調べます。そして、すべて定数の場合は、そのレンジ式を1つのレンジ定数で置き換えます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveには単精度データ型(single precision data
type)にたいするサポートがおり、Octave内のほとんどの関数は、単精度値を受け入れ、単精度の答えをリターンします。単精度変数は、single関数で作成します。
xを単精度型に変換します。
See also: double.
たとえば:
sngl = single (rand (2, 2))
⇒ sngl =
0.37569 0.92982
0.11962 0.50876
class (sngl)
⇒ single
|
多くの関数は、単精度値を直接リターンすることもできます。たとえば
ones (2, 2, "single") zeros (2, 2, "single") eye (2, 2, "single") rand (2, 2, "single") NaN (2, 2, "single") NA (2, 2, "single") Inf (2, 2, "single") |
これはすべて単精度マトリクスをリターンします。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveは倍精度を使用する代替えとして、整数マトリクスをサポートします。8、16、32、64ビットで表される、符号つき、および符号なし整数の両方が使用できます。整数は数値演算により型が変化するときがあるので、多くの演算では浮動小数点データが要求されることは注記しておくべきでしょう。この理由により、整数がもっとも使用されるのは計算ではなく、データの格納においてです。
一般的に、整数マトリクスのほとんどは、既存のマトリクスを整数にキャストすることにより作成されます。以下は、マトリクスを32ビット整数にキャストする方法の例です。
float = rand (2, 2)
⇒ float = 0.37569 0.92982
0.11962 0.50876
integer = int32 (float)
⇒ integer = 0 1
0 1
|
確認できるように、浮動小数点値は変換時にもっとも近い整数に丸められます。
xが整数オブジェクト(int8、uint8、int16、など)の場合はtrueをリターンします。Octave内部では数値定数は倍精度浮動小数点値なので、isinteger
(14)はfalseになることに注意してください。
xを8ビット整数型に変換します。
See also: uint8, int16, uint16, int32, uint32, int64, uint64.
xを符号なし8ビット整数型に変換します。
See also: int8, int16, uint16, int32, uint32, int64, uint64.
xを16ビット整数型に変換します。
See also: int8, uint8, uint16, int32, uint32, int64, uint64.
xを符号なし16ビット整数型に変換します。
xを32ビット整数型に変換します。
See also: int8, uint8, int16, uint16, uint32, int64, uint64.
xを符号なし32ビット整数型に変換します。
xを64ビット整数型に変換します。
See also: int8, uint8, int16, uint16, int32, uint32, uint64.
xを符号なし64ビット整数型に変換します。
整数型として表すことができる、もっとも大きな整数をリターンします。変数typeは
int8signed 8-bit integer.
int16符号つき16ビット整数
int32符号つき32ビット整数
int64符号つき64ビット整数
uint8符号なし8ビット整数
uint16符号なし16ビット整数
uint32符号なし32ビット整数
uint64符号なし64ビット整数
typeのデフォルト値はint32です。
整数型として表すことができる、もっとも小さな整数をリターンします。変数typeは
int8signed 8-bit integer.
int16符号つき16ビット整数
int32符号つき32ビット整数
int64符号つき64ビット整数
uint8符号なし8ビット整数
uint16符号なし16ビット整数
uint32符号なし32ビット整数
uint64符号なし64ビット整数
typeのデフォルト値はint32です。
浮動小数点値として一貫(consecutively)して表すことができる、最大の整数をリターンします。デフォルトクラスは"double"ですが、"single"も有効なオプションです。IEEE-754互換システムでは、flintmaxは"double"にたいして2^53、"single"にたいして2^24です。
| 4.4.1 Integer Arithmetic |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
整数に適用できない数値演算はたくさんありますが、Octaveは整数にたいして加算や乗算のような基本的な操作をサポートします。同じ型の整数にたいして+、-、.*、./の演算子が機能します。つまり2つの32ビット整数の加算はできますが、32ビット整数と16ビット整数の加算はできません。
整数演算を行う場合、アンダーフローとオーバーフローの可能性を考慮すべきです。これは選択した整数型を使用して、演算結果を表現できないときに発生します。たとえば、符号なし整数を使用している場合は、10 - 20の結果は表現できません。そのような場合、Octaveは整数演算の結果を、真の結果に近い整数にします。したがって10 - 20の結果は、符号なし整数を使用している場合は0になります。
整数の除算では、Octaveは結果をもっとも近い整数に丸めます。多くの言語では結果はもっとも近い整数に切り下げる場合が多いので、Octaveとは異なります。Octaveでは、int32
(5) ./ int32 (8)の結果は1になります。
別の丸め規則により整数の除算を行います。
標準では、a ./
bのような整数除算にたいして、結果はもっとも近い整数に丸められます。これは常に望んだ振る舞いではないため、idiqvideは要素ごとの除算による少数部にたいして、opフラグにより異なる扱いをします。opは以下の文字列です:
"fix"a ./ bを計算して、少数部を0に丸めます。
"round"a ./ bを計算して、少数部をもっとも近い整数に丸めます。
"floor"a ./ bを計算して、少数部を負の無限大に丸めます。
"ceil"a ./ bを計算して、少数部を正の無限大に丸めます。
以下の例は、opにデフォルト"fix"以外が与えられた場合の、これらの丸め規則の実例です
idivide (int8 ([-3, 3]), int8 (4), "fix") ⇒ int8 ([0, 0]) idivide (int8 ([-3, 3]), int8 (4), "round") ⇒ int8 ([-1, 1]) idivide (int8 ([-3, 3]), int8 (4), "floor") ⇒ int8 ([-1, 0]) idivide (int8 ([-3, 3]), int8 (4), "ceil") ⇒ int8 ([0, 1]) |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveは、数値をビット単位で操作するいくつかの関数を提供します。特定のビットの値のセットと取得を行う基本的な関数は、bitsetとbitgetです。
A内の符号なし整数のnビットにたいして、セットまたはリセットを行います。val = 0の場合はリセット、val = 1の場合はセットを行います。最小の有効なビットは、n = 1です。すべての変数は同サイズまたは、スカラーでなければなりません。
dec2bin (bitset (10, 1)) ⇒ 1011 |
See also: bitand, bitor, bitxor, bitget, bitcmp, bitshift, bitmax.
符号なし整数A内の、ビットnの状態をリターンします。有効な最小のビットはn = 1です。
bitget (100, 8:-1:1) ⇒ 0 1 1 0 0 1 0 0 |
See also: bitand, bitor, bitxor, bitset, bitcmp, bitshift, bitmax.
Octaveのビット単位操作の引数はすべて、bitcmpを除き、スカラーまたは配列を指定できます(bitcmpの引数kはスカラーでなければなりません)。1つ以上の引数が配列の場合は、すべての引数が同じ形状でなければならず、ビット単位操作は引数の個別の要素ごとに適用されます。少なくとも1つの引数がスカラーで、配列もある場合は、スカラー引数が複製されます。したがって
bitget (100, 8:-1:1) |
は、以下と同じです
bitget (100 * ones (1, 8), 8:-1:1) |
Octaveのビット操作関数に渡されるすべての値は、整数として扱われることを注記しておくべきでしょう。師、たとえ上記の例のbitsetに浮動小数点値10を渡しても、10にたいする浮動小数点フォーマットのネイティブ表現ではなく、ビット[1,
0, 1, 0]として扱われます。
ビット操作にとって、数値として表すことのできる最大値は、特にマスク処理を行う場合に重要なので、Octaveは関数bitmaxを提供します。
浮動小数点値として表すことのできる最大の整数値をリターンします。デフォルトクラスは"double"ですが、"single"も有効なオプションです。IEEE-754互換システムでのbitmaxは、"double"にたいしては2^53
- 1、"single"にたいしては2^24 -1です。
これは前に説明した関数intmaxの倍精度バージョンです。
Octaveにはビット単位の演算子、’積(and)’、’和(or)’、’排他的論理和(exclusive or)’もあります。
非負の整数のビットごとのANDをリターンします。xとyは、レンジ[0,bitmax]以内でなければなりません。
See also: bitor, bitxor, bitset, bitget, bitcmp, bitshift, bitmax.
非負の整数のビットごとのORをリターンします。xとyは、レンジ[0,bitmax]以内でなければなりません。
See also: bitor, bitxor, bitset, bitget, bitcmp, bitshift, bitmax.
非負の整数のビットごとのXORをリターンします。xとyは、レンジ[0,bitmax]以内でなければなりません。
See also: bitand, bitor, bitset, bitget, bitcmp, bitshift, bitmax.
ビット単位の’否定(not)’は、値の各ビットにたいして論理否定を行う、単項演算子です。これは否定しようとする値のマスクを定義しなければならないときに有用です。Octaveのビットごとの’否定(not)’演算子は、bitcmpです。
A内の整数のkビット補数をリターンします。kは省略された場合、k = log2 (bitmax) +
1が指定されたとみなします。
bitcmp (7,4) ⇒ 8 dec2bin (11) ⇒ 1011 dec2bin (bitcmp (11, 6)) ⇒ 110100 |
See also: bitand, bitor, bitxor, bitset, bitget, bitcmp, bitshift, bitmax.
Octaveには、値にたいしてビット単位での左シフトと右シフトの機能もあります。
a内の符号なし整数をkビットシフトして、結果のn桁(ビット)をリターンします。kの値が正ならば左シフト、負ならば右シフトです。nが省略された場合のデフォルトは、log2(bitmax)+1です。nはレンジ[1,log2(bitmax)+1](通常は[1,33])以内でなければなりません。
bitshift (eye (3), 1) ⇒ 2 0 0 0 2 0 0 0 2 bitshift (10, [-2, -1, 0, 1, 2]) ⇒ 2 5 10 20 40 |
See also: bitand, bitor, bitxor, bitset, bitget, bitcmp, bitmax.
値の両方の終端からシフトアウトされたビットは失われます。Octaveは数学的シフト(右シフトにおいて値の符号ビットが保持される)も使用します。たとえば:
bitshift (-10, -1) ⇒ -5 bitshift (int8 (-1), -1) ⇒ -1 |
bitshift (int8 (-1),
-1)が-1になることに注意してください。これはint8データ型における-1のビット表現が[1,
1, 1, 1, 1, 1, 1, 1]だからです。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveには論理値(例:
値がtrueかfalseであるような変数)にたいするビルトインサポートがあります。2つの変数を比較する場合、結果はその比較の結果が真か否かに依存する値をもつ、論理値になります。
基本的な論理演算子&、|、!はそれぞれ“論理AND”、“論理OR”、“論理NOT”に対応します。これらの演算子は通常の論理ルールにしたがいます。
標準的な数値計算の一部として論理値を使うこともできます。この場合、trueは1、falseは0に変換され、それらは倍精度浮動小数点数で表されます。つまりtrue*22
- false/6は22になります。
論理値はマトリクスとセル配列のインデクスにも使用されます。論理配列でインデクス操作を行う場合、結果は論理配列のtrue部に対応する値を含むベクターになります。以下の例で示します。
data = [ 1, 2; 3, 4 ];
idx = (data <= 2);
data(idx)
⇒ ans = [ 1; 2 ]
|
idx配列を作成せずに、上記コードのdata(idx)をdata( data <= 2
)に置き換えることも可能です。
論理値は、数値オブジェクトから論理値へのキャストや、trueおよびfalseの関数で構築することもできます。
数値オブジェクトxを論理型に変換します。
非0値はtrue(1)に、0値はfalse(0)に変換されます。非数値NaNは変換できず、エラーが発生します。
互換性ノート: Octaveでは複素数値を入力できますが、MATLABはできません。
要素がすべて論理的1であるような行列またはN次元配列をリターンします。引数が1つのスカラー整数の場合は、指定されたサイズの正方マトリクスリターンします。引数が2つ以上のスカラー整数、または整数値ベクターの場合は、与えられた次元の配列をリターンします。
See also: false.
要素がすべて論理的0であるような行列またはN次元配列をリターンします。引数が1つのスカラー整数の場合は、指定されたサイズの正方マトリクスリターンします。引数が2つ以上のスカラー整数、または整数値ベクターの場合は、与えられた次元の配列をリターンします。
See also: true.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
混成されたデータ型にたいして機能する演算子と関数が多数あります。たとえば、
uint8 (1) + 1
⇒ 2
|
上記の例の演算子は、8ビット整数と倍精度値に作用して、8ビット整数値をリターンしています。型は期待されるように倍精度値に昇格されるのではなく、8ビット整数に降格されたことに注意してください。この理由は、Octaveで上記のような式内の値が昇格されるには、下記のようにすべての数値定数を適切な型に明示的にキャストする必要があるからです
uint8 (1) + uint8 (1)
⇒ 2
|
これはユーザーにとって一律に受け入れることを困難にし、混入されるバグの発見を難しくするかもしれません。同じことは、以下のような単精度値にたいする混成演算にも適用されます
single (1) + 1
⇒ 2
|
これは単精度値をリターンします。有効な混成演算と、それらがリターンするデータ型は以下のとおりです
| 混成演算 | 結果 | ||
|---|---|---|---|
| double OP single | single | ||
| double OP integer | integer | ||
| double OP char | double | ||
| double OP logical | double | ||
| single OP integer | integer | ||
| single OP char | single | ||
| single OP logical | single |
以下のような混成引数による関数呼び出しにも、同じロジックが適用されます
min (single (1), 0) ⇒ 0 |
これのリターン値は単精度です。
混成型によるインデクス割り当てでは、型は変更されません。たとえば、
x = ones (2, 2);
x(1, 1) = single (2)
⇒ x = 2 1
1 1
|
ここではxは倍精度型のままです。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
変数のデータ型はプログラム実行の間に変更されるかもしれないので、実行時に型チェックを行う必要が生じます。型チェックを行うことにより、入力のデータ型により関数の振る舞いを変化させることもできます。以下は入力が実数の場合は絶対値、複素数の場合は長さをリターンする、absの単純な実装例です
function a = abs (x)
if (isreal (x))
a = sign (x) .* x;
elseif (iscomplex (x))
a = sqrt (real(x).^2 + imag(x).^2);
endif
endfunction
|
以下の関数は変数の型を判断するために利用できます。
xが数値オブジェクト(例: 整数、実数、複素数の配列など)の場合は、trueをリターンします。論理値と文字配列は、数値とは判断されません。
See also: isinteger, isfloat, isreal, iscomplex, islogical, ischar, iscell, isstruct, isa.
xが浮動小数点数値オブジェクトの場合は、trueをリターンします。倍精度と単精度クラスのオブジェクトは浮動小数点オブジェクトです。
xが複素数のマトリクスおよびスカラーでない場合は、trueをリターンします。MATLABとの互換性のため、論理値と文字マトリクスを含みます。
xが複素数の値をもつ数値オブジェクトの場合は、trueをリターンします。
See also: isreal, isnumeric, islogical, ischar, isfloat, isa.
aがマトリクス、論理値、文字マトリクスの場合は、trueをリターンします。スカラー(1x1マトリクス)とベクター(1xNマトリクスまたはNx1マトリクスは、一般的なN次元マトリクスのサブセットなので、これらのオブジェクトにたいしてもismatrixは同じようにtrueをリターンします。
See also: isscalar, isvector, iscell, isstruct, issparse, isa.
xがベクターの場合は、trueをリターンします。ベクターはどちらか一方の次元が1に等しい2次元配列です。したがって1x1配列とスカラーもベクターです。
xが行ベクターの場合は、trueをリターンします。
xが列ベクターの場合は、trueをリターンします。
xが正方マトリクスの場合は、trueをリターンします。
xがtolで指定された公差内で対称なマトリクスの場合は、trueをリターンします。デフォルトの公差は0です(高速なコードを使用します)。マトリクスtolは、norm
(x - x.', Inf) / norm (x, Inf) < tolの場合は、対称と判断されます。
See also: ishermitian, isdefinite.
xがtolで指定された公差内でエルミートの場合は、trueをリターンします。デフォルトの公差は0です(高速なコードを使用します)。マトリクスxは、norm
(x - x', Inf) / norm (x, Inf) < tolであれば対称と判断されます。
See also: issymmetric, isdefinite.
xがtolで指定された公差内で対称な正定値であれば1、xが対称な半正定値であれば0、それ以外は-1をリターンします。tolが省略された場合は、公差100
* eps * norm (x, "fro")を使用します。
See also: issymmetric, ishermitian.
xが論理オブジェクトの場合は、trueをリターンします。
xの要素にたいして、素数の要素にたいしてはtrue、それ以外はfalseであるような論理配列をリターンします。
x内の最大値が非常に大きい場合は、特別な目的のための因数分解コードを使用するべきです。
isprime (1:6)
⇒ [0, 1, 1, 0, 1, 0]
|
変数のプロパティを調べるのではなく、どの変数が定義されているかや、ワークスペース自体についての情報を収集したい場合は、Status of Variablesを参照してください。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
文字列定数(string constant)は、ダブルクォーテーションマークまたはシングルクォーテーションマークで囲まれた、文字シーケンスにより構成されます。たとえば、以下の式
"parrot" 'parrot' |
はどちらも内容が‘parrot’の文字列を表します。Octaveでは文字列は任意の長さをとることができます。
シングルクォートマークは転置演算子(Arithmetic Operators参照)にも使用されますが、ダブルクォートマークはOctaveでは他の目的に使用されることはないので、文字列を表すときはダブルクォートマークを使うのが最善です。
文字列の連結はマトリクス定義の記法を使用できます。たとえば、以下の式
[ "foo" , "bar" , "baz" ] |
は、内容が‘foobarbaz’の文字列を生成します。マトリクスの作成についての詳細は、Numeric Data Typesを参照してください。
| 5.1 Escape Sequences in String Constants | ||
| 5.2 Character Arrays | ||
| 5.3 Creating Strings | ||
| 5.4 Comparing Strings | ||
| 5.5 Manipulating Strings | ||
| 5.6 String Conversions | ||
| 5.7 Character Class Functions |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
ダブルクォートされた文字列内では、バックスラッシュ文字は他の文字を表すためのエスケープシーケンスとして使用されます。 In double-quoted strings, the backslash character is used to introduce that represent other characters. たとえば‘\n’はダブルクォートされた文字列内に改行文字を、‘\"’はダブルクォート文字を埋め込みます。シングルクォートされた文字列内では、バックスラッシュ文字は特別な文字ではありません。以下の例は、この違いを示します:
toascii ("\n")
⇒ 10
toascii ('\n')
⇒ [ 92 110 ]
|
以下は、Octaveで(ダブルクォートされた文字列内で)使用されるすべてのエスケープシーケンスのテーブルです。これらはCプログラミング言語で使用される場合と同じです。
\\リテラルにバックスラッシュ‘\’を表します。
\"リテラルのダブルクォート文字‘"’を表します<。
\'リテラルのシングルクォート文字‘'’を表します。
\0Null文字(control-@、ASCIIコード0)を表します。
\a“alert”文字(control-g、ASCIIコード7)を表します。
\bバックスペース(control-h、ASCIIコード8)を表します。
\f改ページ(control-l、ASCIIコード12)を表します。
\n改行(control-j、ASCIIコード10)を表します。
\rキャリッジリターン(control-m、ASCIIコード13)を表します。
\t水平タブ(control-i、ASCIIコード9)を表します。
\v垂直タブ(control-k、ASCIIコード11)を表します。
\nnn8進値nnnの文字を表します。nnnは0から7の1桁から3桁です。たとえば、アスキーのESC文字は‘\033’です。
\xhh…16進値hhの文字を表します。hhは16進数字(‘0’から‘9’、および‘A’から‘F’または‘a’から‘f’)です。 ANSI-Cの場合と同様、最初の非16進数字が見つかるエスケープシーケンスは継続されます。しかし3桁以上の16進数字は未定義の結果を生成します。
シングルクォートされた文字列内のエスケープシーケンスは、1つだけです。連続してシングルクォート文字を使用することにより、1つのシングルクォート文字を挿入できます。たとえば、
'I can''t escape'
⇒ I can't escape
|
スクリプト内では、必要ならis_dq_stringとis_sq_stringを使用して、2つの文字列型を区別できます。
xがダブルクォートされた文字列の場合は、trueをリターンします。
See also: is_sq_string, ischar.
xがシングルクォートされた文字列の場合は、trueをリターンします。
See also: is_dq_string, ischar.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
文字列を表すためにOctaveが使用するのは文字の配列なので、文字列"dddddddddd"は、内部的にはすべての要素が値100(100は"d"のASCIIコード)の長さが10の行ベクターです。これは文字マトリクスにたいする明白な汎化をもたらします。文字マトリクスを使用することにより、同じ長さに文字列コレクションを、1つの変数で表すことが可能になります。Octave内で使用される慣習では、文字マトリクスの各行が個別の文字列になりますが、各列で文字列を表すことも同様に可能です。
文字マトリクスを作成するもっとも簡単な方法は、複数の文字列を一緒にマトリクスに配す方法です。
collection = [ "String #1"; "String #2" ]; |
これは2行9列の文字マトリクスを作成します。
関数ischarは、オブジェクトが文字マトリクスかテストするために使用できます。
xが文字配列の場合は、trueをリターンします。
See also: isfloat, isinteger, islogical, isnumeric, iscellstr, isa.
オブジェクトが文字列(例:
文字ベクターか、文字マトリクスでないか、など)なのかテストするためには、以下の例のようにisvector関数を組み合わせてischar関数を使用できます。
ischar (collection)
⇒ 1
ischar (collection) && isvector (collection)
⇒ 0
ischar ("my string") && isvector ("my string")
⇒ 1
|
これに関係して疑問が1つ生じます。異なる長さの文字列から文字マトリクスを作成すると何が起こるでしょうか。短い文字列の最後にOctaveがブランク文字を追加する、というのが答えです。string_fill_char関数を使えば、ブランク文字以外の文字を使うこともできます。
文字マトリクスのすべての行を同じ長さにパディングするために使用される内部変数にたいして、問い合わせまたはセットを行います。これは1文字でなければなりません。デフォルト値は"
"(スペース1つ)です。たとえば:
string_fill_char ("X");
[ "these"; "are"; "strings" ]
⇒ "theseXX"
"areXXXX"
"strings"
|
関数内部から"local"オプションと共に呼び出された場合、変数の変更はその関数または関数のサブルーチンにたいしてローカルになります。関数をexitするときに、変数の元の値がリストアされます。
これは文字マトリクスの問題点を表しています。文字マトリクスでは、長さの異なる文字列の表現は単に不可能なのです。解決策は文字列のセル配列の使用です。これはCell Arrays of Stringsで説明されています。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
文字列を作成するもっとも簡単な方法は、冒頭で紹介したように、テキストをダブルクォートかシングルクォートで囲む方法です。しかし、実際にテキストを記述せずに文字列を作成することも可能です。関数blanksはブランク文字(ASCIIコード32)だけで構成される、与えられた長さの文字列を作成します。
n個のブランクからなる文字列をリターンします。
blanks (10);
whos ans
⇒
Attr Name Size Bytes Class
==== ==== ==== ===== =====
ans 1x10 10 char
|
See also: repmat.
| 5.3.1 Concatenating Strings | ||
| 5.3.2 Converting Numerical Data to Strings |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
文字列はマトリクス表記(StringsおよびCharacter Arraysを参照)を使用して作成することができます。これがもっとも自然な方法の場合もあります。たとえば:
fullname = [fname ".txt"]; email = ["<" user "@" domain ">"]; |
どちらの場合も、最終的にどのような文字列になるか容易に判断できます。この方法は、もっとも効率的でもあります。マトリクス結合を使用するとき、パーサーは関数呼び出しと関数による入力の検査というオーバーヘッドなしに、即座に文字列の連結を開始します。
それでも、特定の状況において文字列オブジェクトを連結する関数がいくつかあります:
char、strvcat、strcat、cstrcatそして最後に一般的な用途のための連結関数が使用できます。horzcatとvertcatを参照してください。
cstrcatを除く
すべての文字列連結関数は以下の例のように、数値を対応するASCII文字に変換することにより、各要素を文字データに変換します:
char ([98, 97, 110, 97, 110, 97]) ⇒ banana |
charとstrvcatは垂直に、strcatとcstrcatは水平に連結します。たとえば、
char ("an apple", "two pears")
⇒ an apple
two pears
strcat ("oc", "tave", " is", " good", " for you")
⇒ octave is good for you
|
charは入力内の空文字列ごとに、出力内に空行を生成します。
一方、strvcatは空文字列を無視します。
char ("orange", "green", "", "red")
⇒ orange
green
red
strvcat ("orange", "green", "", "red")
⇒ orange
green
red
|
cstrcatを除くすべての文字列連結関数は、
セル配列データも受け付けます(Cell Arrays)。charとstrvcatはセル配列を文字配列に変換し、strcatはセル配列内のセルを連結します:
char ({"red", "green", "", "blue"})
⇒ red
green
blue
strcat ({"abc"; "ghi"}, {"def"; "jkl"})
⇒
{
[1,1] = abcdef
[2,1] = ghijkl
}
|
strcatは引数(セル配列を除く)の末尾のスペースを削除しますが、
cstrcatはそのまま残します。以下の例のように、この2種類を使い分けるのが便利なときもあります:
strcat (["dir1";"directory2"], ["/";"/"], ["file1";"file2"])
⇒ dir1/file1
directory2/file2
cstrcat (["thirteen apples"; "a banana"], [" 5$";" 1$"])
⇒ thirteen apples 5$
a banana 1$
|
上記のcstrcatの例の空白文字は、文字列配列内での文字列の内部表現にもとづくことに注意してください(Character Arraysを参照)。
2つ以上の数値マトリクス、文字マトリクス、セル配列から文字列配列を作成します。引数は垂直に結合されます。リターン値は、文字列配列の各行の文字列が同じ長さになるように、必要に応じブランクでぱっパディングされます。空の入力文字列には意味があり、出力に連結されます。
数値入力では、各要素は対応するASCII文字に変換されます。入力がASCII(0から255)の範囲外の場合、結果はレンジエラーになります。
セル配列では、各要素は個々に連結されます。charにより変換されたセル配列の大部分は、cellstrで元に変換できます。たとえば:
char ([97, 98, 99], "", {"98", "99", 100}, "str1", ["ha", "lf"])
⇒ ["abc "
" "
"98 "
"99 "
"d "
"str1 "
"half "]
|
2つ以上の数値マトリクス、文字マトリクス、セル配列から文字配列を作成します。。引数は垂直に連結します。リターン値は、文字列配列の各要素が同じ長さになるように、必要に応じブランクでパディングされます。
charと異なり、空文字列は削除され、出力されません
数値入力では、各要素は対応するASCII文字に変換されます。入力がASCII(0から255)の範囲外の場合、結果はレンジエラーになります。
セル配列では、各要素は個々に連結されます。strvcatで変換されたセル配列の大部分は、cellstrで元に変換できます。たとえば:
strvcat ([97, 98, 99], "", {"98", "99", 100}, "str1", ["ha", "lf"])
⇒ ["abc "
"98 "
"99 "
"d "
"str1 "
"half "]
|
すべての引数を水平に連結した文字列をリターンします。引数がセル文字列の場合、strcatは個々のセルを連結したセル文字列をリターンします。入力が数値の場合、各要素は対応するASCII文字に変換されます。入力文字列の末尾の空白文字は、文字列を連結する前に削除されます。セル文字列にはトリムされた空白文字を含まないことに注意してください。
たとえば:
strcat ("|", " leading space is preserved", "|")
⇒ | leading space is preserved|
|
strcat ("|", "trailing space is eliminated ", "|")
⇒ |trailing space is eliminated|
|
strcat ("homogeneous space |", " ", "| is also eliminated")
⇒ homogeneous space || is also eliminated
|
s = [ "ab"; "cde" ];
strcat (s, s, s)
⇒
"ababab "
"cdecdecde"
|
s = { "ab"; "cd " };
strcat (s, s, s)
⇒
{
[1,1] = ababab
[2,1] = cd cd cd
}
|
すべての引数を水平に連結した文字列をリターンします。末尾のスペースは残されます。たとえば:
cstrcat ("ab ", "cd")
⇒ "ab cd"
|
s = [ "ab"; "cde" ];
cstrcat (s, s, s)
⇒ "ab ab ab "
"cdecdecde"
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
数値データを対応するASCII文字にキャストする文字列連結関数(Concatenating Strings参照)の他にも、数値データを文字列にフォーマットする関数がいくつかあります。mat2strとnum2strは実数おとび複素数のマトリクス、int2strは整数マトリクスを変換します。
複素数値にたいしてint2strは、実数部から少数部を整数に丸めて評価します。数値データを文字列にフォーマットする、より柔軟な方法としては、sprintf関数(Formatted Output, sprintf参照)があります。
実数、複素数、および論理のマトリクスw文字列としてフォーマットします。リターンされる文字列とeval関数を使用することにより、元のマトリクスを再構築できます。
値の精度は、nにより与えられます。nがスカラーの場合、マトリクスの実数部と虚数部は両方とも同じ精度でプリントされます。スカラーでない場合は、n(1)が実数部の精度、n(2)が虚数部の精度を定義します。nのデフォルト値は15です。
引数"class"が与えられた場合には、evalがそのクラスのマトリクスを構築するときのような方法で、xが文字列結果に含められます。
mat2str ([ -1/3 + i/7; 1/3 - i/7 ], [4 2])
⇒ "[-0.3333+0.14i;0.3333-0.14i]"
mat2str ([ -1/3 +i/7; 1/3 -i/7 ], [4 2])
⇒ "[-0.3333+0i 0+0.14i;0.3333+0i -0-0.14i]"
mat2str (int16 ([1 -1]), "class")
⇒ "int16([1 -1])"
mat2str (logical (eye (2)))
⇒ "[true false;false true]"
isequal (x, eval (mat2str (x)))
⇒ 1
|
数字(または配列)を、文字列(または文字配列)に変換します。オプションの第2引数は、出力に使用される有効桁数(precision)、またはsprintf形式(Formatted Output参照)のフォーマット用テンプレート文字列(format)です。num2strは複素数も扱うことができます。
例:
num2str (123.456)
⇒ "123.46"
num2str (123.456, 4)
⇒ "123.5"
s = num2str ([1, 1.34; 3, 3.56], "%5.1f")
⇒ s =
1.0 1.3
3.0 3.6
whos s
⇒
Attr Name Size Bytes Class
==== ==== ==== ===== =====
s 2x8 16 char
num2str (1.234 + 27.3i)
⇒ "1.234+27.3i"
|
注意:
MATLABとの互換性のため、文字列をリターンする前に先頭のスペースは削除されます。
num2str関数はあまり柔軟ではありません。より柔軟に結果を制御したい場合は、sprintf(Formatted Output参照)を使用してください。
xが複素数の場合は、フォーマット文字列に含める出力変換指定は1つだけにしてください。それ以外では、結果は予測できません。
整数(または整数配列)を、文字列(または文字配列)に変換します。
int2str (123)
⇒ "123"
s = int2str ([1, 2, 3; 4, 5, 6])
⇒ s =
1 2 3
4 5 6
whos s
⇒
Attr Name Size Bytes Class
==== ==== ==== ===== =====
s 2x7 14 char
|
この関数はあまり柔軟ではありません。より柔軟に結果を制御したい場合は、sprintf(Formatted Output参照)を使用してください。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
文字列とは文字配列のことなので、以下の例が示すように、文字列は要素ごとに比較されます。
GNU = "GNU's Not UNIX";
spaces = (GNU == " ")
⇒ spaces =
0 0 0 0 0 1 0 0 0 1 0 0 0 0
|
To determine if two strings are identical it is necessary to use the
2つの文字列が等しいか判断するには、strcmp関数を使う必要があります。この関数は大文字小文字を区別して、文字列全体を比較します。strncmpは、最初のN文字だけを比較します(Nはパラメーターとして与えられます)。strcmpiとstrncmpiは、大文字小文字を区別しません。
文字列s1とs2が同じなら1、それ以外は0をリターンします。
s1とs2のいずれかが文字列のセル配列の場合、個々のセル配列にたいして上述した値を含む、セル配列と同じサイズの配列をリターンします。もう一方の引数は文字列のセル配列(同じサイズ、または要素が1つだけのセル配列)、文字マトリクス、または文字列です。
警告: MATLABとの互換性のため、Octaveのstrcmp関数は文字列が等しいときに1、等しくなければ0をリターンします。これは同名のCライブラリー関数とは逆です。
文字列s1とs2の最初のn文字が同じなら1、それ以外は0をリターンします。
strncmp ("abce", "abcd", 3)
⇒ 1
|
s1とs2のいずれかが文字列のセル配列の場合、個々のセル配列にたいして上述した値を含む、セル配列と同じサイズの配列をリターンします。もう一方の引数は文字列のセル配列(同じサイズ、または要素が1つだけのセル配列)、文字マトリクス、または文字列です。
strncmp ("abce", {"abcd", "bca", "abc"}, 3)
⇒ [1, 0, 1]
|
警告: MATLABとの互換性のため、Octaveのstrncmp関数は文字列が等しいときに1、等しくなければ0をリターンします。これは同名のCライブラリー関数とは逆です。
文字列s1とs2が、同じ(大文字小文字の違いは無視)場合は1、それ以外は0をリターンします。
s1とs2のいずれかが文字列のセル配列の場合、個々のセル配列にたいして上述した値を含む、セル配列と同じサイズの配列をリターンします。もう一方の引数は文字列のセル配列(同じサイズ、または要素が1つだけのセル配列)、文字マトリクス、または文字列です。
警告: MATLABとの互換性のため、Octaveのstrcmpi関数は文字列が等しいときに1、等しくなければ0をリターンします。これは同名のCライブラリー関数とは逆です。
警告: National alphabetはサポートされません。
s1とs2の最初のn文字が同じ(大文字小文字の違いは無視)場合は1、それ以外は0をリターンします。
s1とs2のいずれかが文字列のセル配列の場合、個々のセル配列にたいして上述した値を含む、セル配列と同じサイズの配列をリターンします。もう一方の引数は文字列のセル配列(同じサイズ、または要素が1つだけのセル配列)、文字マトリクス、または文字列です。
警告: MATLABとの互換性のため、Octaveのstrncmpi関数は文字列が等しいときに1、等しくなければ0をリターンします。これは同名のCライブラリー関数とは逆です。
警告: National alphabetsはサポートされません。
strがstrarray内の要素、または要素の部分文字列か検証します。
strがテストされる文字列で、strarrayが有効な値となる文字列のセル配列の場合、validstrはstrにたいする検証フォームです(検証の定義はstrがvalidstrのメンバー、またはメンバーの部分文字列かどうかです)。これはオプションの長い形式が"red"で短い形式が"r"のような場合などに、短い形式を展開して検証するのに便利です。strがvalidstrの部分文字列で複数がマッチし、すべてのマッチが部分文字列へのマッチの場合は、最短のマッチがリターンされます。それ以外では、strの展開があいまいなため、エラーがレイズされます。すべての比較で大文字小文字を区別しません。
追加入力のfuncname、varname、positionはオプションで、生成される検証エラーメッセージをより具体的にするものです。
例:
validatestring ("r", {"red", "green", "blue"})
⇒ "red"
validatestring ("b", {"red", "green", "blue", "black"})
⇒ error: validatestring: multiple unique matches were found for 'b':
blue, black
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveは文字列を操作するための関数を広範にサポートします。文字列は単なるマトリクスなので、単純な操作は標準的な演算子を使用して行うことができます。以下はブランク文字をすべてアンダースコアで置き換える方法を示す例です。
quote = ...
"First things first, but not necessarily in that order";
quote( quote == " " ) = "_"
⇒ quote =
First_things_first,_but_not_necessarily_in_that_order
|
検索、置換、および一般的な正規表現などのより複雑な操作にたいして、Octaveには以下の関数があります。
sから末尾の空白文字とnullを削除します。sがマトリクスの場合、deblankは各行をもっとも長い文字列の長さにトリムします。sが文字列のセル配列の場合は、各文字列要素を再帰的に処理します。
例:
deblank (" abc ")
⇒ " abc"
deblank ([" abc "; " def "])
⇒ [" abc " ; " def"]
|
See also: strtrim.
sから先頭と末尾の空白文字を削除します。sがマトリクスの場合、strtrimは各行をもっとも長い文字列の長さにトリムします。sが文字列のセル配列の場合は、各文字列要素を再帰的に処理します。たとえば:
strtrim (" abc ")
⇒ "abc"
strtrim ([" abc "; " def "])
⇒ ["abc " ; " def"]
|
See also: deblank.
文字列sを、長さnに切り詰めます。sが文字マトリクスのは、列数を合わせます。sが文字列のセル配列の場合は、処理は各要素にたいして行われ、新たなセル配列をリターンします。
文字列sとtの長い方の文字列中で、短い方の文字列が出現するすべての位置をベクターでリターンします。オプション引数overlapがtrueの場合は、リターンされるベクターはオーバーラップする位置を含むことができます(これがデフォルトです)。たとえば:
findstr ("ababab", "a")
⇒ [1, 3, 5];
findstr ("abababa", "aba", 0)
⇒ [1, 5]
|
警告: findstrは廃止が予定されています。新たなコードはすべてstrfindを使用してください。
See also: strfind, strmatch, strcmp, strncmp, strcmpi, strncmpi, find.
文字列charsから、文字集合charsの文字の出現を検索します。リターン値、および引数のnとdirectionは、findの場合と同様に振る舞います。
多くの場合、この関数はregexpを使用するより高速です。
See also: find.
文字列s内で文字列tが最初に出現する位置、見つからない場合は0をリターンします。sには文字列配列、または文字列のセル配列も指定できます。
たとえば:
index ("Teststring", "t")
⇒ 4
|
directionが"first"の場合は、見つかった最初の要素をリターンします。directionが"last"の場合は、見つかった最後の要素をリターンします。
文字列s内で文字列tが最後に出現する位置、見つからない場合は0をリターンします。sには文字列配列、または文字列のセル配列も指定できます。
たとえば:
rindex ("Teststring", "t")
⇒ 6
|
rindex関数は、directionを"last"にセットしたindex関数と等価です。
文字列str内からpatternを検索して、出現の各開始位置のインデクスをベクターidxでリターンします。
パターンが見つからなかった場合、またはpatternがstrより長い場合には、idxは空の配列[]になります。オプション引数"overlaps"はパターンがstr内のどの位置でもマッチする(true)か、完全なパターンのユニークな出現だけにマッチする(false)を決定します。デフォルトはtrueです。
文字列のセル配列 cellstrがセットされた場合、idxは上記で指定されたベクターのセル配列になります。
例:
strfind ("abababa", "aba")
⇒ [1, 3, 5]
strfind ("abababa", "aba", "overlaps", false)
⇒ [1, 5]
strfind ({"abababa", "bebebe", "ab"}, "aba")
⇒
{
[1,1] =
1 3 5
[1,2] = [](1x0)
[1,3] = [](1x0)
}
|
セル文字列配列cstrの要素を1つの文字列に結合します。
delimiterが指定されない場合、cstrの要素の区切りはスペースになります。
delimiterが文字列として指定された場合、その文字列を使用してセル文字列配列が結合されます。エスケープシーケンスもサポートされます。
delimiterがセル文字列配列で、その長さがcstrより1小さい場合は、cstrはdelimiterの要素を順番に使って結合されます。エスケープシーケンスはサポートされません。
strjoin ({'Octave','Scilab','Lush','Yorick'}, '*')
⇒ 'Octave*Scilab*Lush*Yorick'
|
See also: strsplit.
sで始まるAのエントリーのインデクスをリターンします。第2引数Aは文字列、文字マトリクス、または文字列のセル配列でなければなりません。第3引数"exact"が与えられなかった場合、sはsの長さまでAに一致するだけでマッチとなります。マッチングでは、sとAの末尾のスペースとnullは無視します。
たとえば:
strmatch ("apple", "apple juice")
⇒ 1
strmatch ("apple", ["apple "; "apple juice"; "an apple"])
⇒ [1; 2]
strmatch ("apple", ["apple "; "apple juice"; "an apple"], "exact")
⇒ [1]
|
警告: strmatchは廃止が予定されています。
Use strncmp (normal case), or strcmp ("exact" case),
or regexp in all new code.
See also: strfind,
findstr, strcmp,
strncmp, strcmpi,
strncmpi, find.
文字列strから、最初に見つかった文字列delim内の文字(その文字は含まない)までのすべての文字を探します。remが要求された場合、remには最初に見つかった区切り文字から開始する、strの残りの文字列がセットされます。str内の先頭の区切り文字は無視されます。delimが指定されない場合には、スペースが指定されたものとします。strには文字列のセル配列を指定することもでき、その場合は個々の文字列にたいして関数が実行され、見つかったトークンと残りの文字がセル配列でリターンされます。
例:
strtok ("this is the life")
⇒ "this"
[tok, rem] = strtok ("14*27+31", "+-*/")
⇒
tok = 14
rem = *27+31
|
delで指定された区切り文字を使用して文字列sを分割し、分割された部分文字列のセル文字列配列をリターンします。区切り文字が指定されない場合、文字列sは空白文字で分割されます。区切り文字delには文字列、スカラーのセル文字列、またはセル文字列配列を指定できます。デフォルトでは入力文字列s内の連続する区切り文字は、1つにまとめられます。
第2出力matchesには元文字列内でマッチした区切り文字がリターンされます。
例:
strsplit ("a b c")
⇒
{
[1,1] = a
[1,2] = b
[1,3] = c
}
strsplit ("a,b,c", ",")
⇒
{
[1,1] = a
[1,2] = b
[1,3] = c
}
strsplit ("a foo b,bar c", {"\s", "foo", "bar"})
⇒
{
[1,1] = a
[1,2] = b
[1,3] = c
}
strsplit ("a,,b, c", {",", " "}, false)
⇒
{
[1,1] = a
[1,2] =
[1,3] = b
[1,4] =
[1,5] = c
}
|
サポートされるname/valueペアー引数は;
simple、
またはregularexpressionを指定できる。デフォルトは、delimitertypeがsimple。
例:
strsplit ("a foo b,bar c", ",|\\s|foo|bar", "delimitertype", "regularexpression")
⇒
{
[1,1] = a
[1,2] = b
[1,3] = c
}
strsplit ("a,,b, c", "[, ]", false, "delimitertype", "regularexpression")
⇒
{
[1,1] = a
[1,2] =
[1,3] = b
[1,4] =
[1,5] = c
}
strsplit ("a,\t,b, c", {',', '\s'}, "delimitertype", "regularexpression")
⇒
{
[1,1] = a
[1,2] = b
[1,3] = c
}
strsplit ("a,\t,b, c", {',', ' ', '\t'}, "collapsedelimiters", false)
⇒
{
[1,1] = a
[1,2] =
[1,3] =
[1,4] = b
[1,5] =
[1,6] = c
}
|
文字列sを1つ以上のセパレーターsepで分割して、文字列のセル配列をリターンします。strip_emptyがtrueでない場合、連続するセパレーター、および境界のセパレーターは、空文字列の結果になります。strip_emptyのデフォルト値はfalseです。
2次元文字配列はセパレーター、および元々の列境界で分割されます。
例:
ostrsplit ("a,b,c", ",")
⇒
{
[1,1] = a
[1,2] = b
[1,3] = c
}
ostrsplit (["a,b" ; "cde"], ",")
⇒
{
[1,1] = a
[1,2] = b
[1,3] = cde
}
|
文字列からデータを読み取ります。
文字列strは、formatの指定に順繰りにマッチする単語に分割されます。つまり、最初の単語は1つ目の指定、次の単語は2つ目の指定にたいするマッチ、のようにとなります。指定子より多くの単語がある場合には、すべての単語が処理されるまで、このプロセスが繰り返されます。
文字列formatには、str内で単語がパースされる方法を記述します。これには以下の指定の任意の組み合わせが含まれます:
%s単語は文字列としてパースされる。
%f%n単語は数字としてパースされ、倍精度に変換される。
%d%u単語は数字としてパースされ、int32に変換される。
%*', '%*f', '%*s単語をスキップする。
%sと%d、%f、%n、%uおよび関連する%*s …は、%N(Nは2以上の整数)によるオプションの幅指定です。%fにたいしては、%N.Mfのような指定ができます。
literalsこれらに加え、フォーマットにはリテラル文字列が含まれる場合があり、これらは読み込みの際にはスキップされます。
パースされた単語は、1つ目の指定子に対応する単語は1つ目の出力引数にリターンされ、残りの指定子も同様です。
formatのデフォルトは"%f"で、これはstrから数字が読み取られることを意味します。これはstrに数値フィールドが含まれるときだけ行われます。
たとえば、文字列
str = "\ Bunny Bugs 5.5\n\ Duck Daffy -7.5e-5\n\ Penguin Tux 6" |
は、以下で読み取ることができます
[a, b, c] = strread (str, "%s %s %f"); |
オプションの数値引数format_repeatは、読み取るアイテム数を制限するために使用できます:
すべての文字列を最後まで読み取る。
nargoutアイテムをN回読み込みます。format_repeatには0を指定することもできます。
プロパティー値ペアーを使って、strreadの挙動を変更できます。以下のプロパティが認識されます:
"commentstyle"strのパーツはコメントと判断され、スキップされる。valueはコメントスタイルで、以下を使用できます。
"shell"
#文字から行末までのすべてがスキップされる。
"c"
/*と*/の間のすべてがスキップされる。
"c++"
//文字から行末までのすべてがスキップされる。
"matlab"
%文字から行末までのすべてがスキップされる。
"delimiter"value内の文字は、strを単語に分割するために使用される(デフォルト値は任意の空白文字)。
"emptyvalue":非空白文字で区切られた空の数値にたいしてリターンする値。デフォルトはNaN。そのデータ型がNaNをサポートしない場合(たとえばint32)のデフォルトは0。
"multipledelimsasone"間に空白文字がない連続する区切り文字のシリーズを、1つの区切り文字として扱う。連続する区切り文字シリーズは垂直に"aligned"(整列されている)必要はない。
"treatasempty"value内の(区切り文字か空白文字で囲まれた)文字列が1つあったら、それを欠損値として扱う。
"returnonerror"valueがtrue(デフォルトは1)の場合は、読み取りエラーを無視して通常どおりリターンする。false(0)の場合は、エラーをリターンする。
"whitespace"value内の任意の文字は空白文字と解釈され、トリムされる。/tのような特殊文字を正しく処理するために、ダブルクォートで囲まなければならない。空白文字のデフォルト値は"
brnt"(スペースが含まれることにに注意)。空白文字が”(空)にセットされておらず"%s"フォーマット変更指定子が1つも指定されていない場合、スペースは常に空白文字の一部となる。
str内の単語数がフォーマット変換指定子の数に正確にマッチしない、strreadの振る舞いはstrの最後の文字に依存する:
"n"データ列は空フィールドかNaNでパディングされるので、すべての列が同じ長さになる
"n"以外データ列はパディングされない。strreadは長さが異なる列をリターンする
文字列str内にあるすべてのパターンptnを文字列repで置換して、その結果をリターンします。
オプション引数"overlaps"は、パターンがstr内のすべての位置でマッチできる(true)か、それとも完全なパターンの一意な出現だけにマッチできるかを決定します。デフォルトはtrueです。
sには文字列のセル配列も指定でき、その場合は各要素にたいして置換が行われ、セル配列がリターンされます。
例:
strrep ("This is a test string", "is", "&%$")
⇒ "Th&%$ &%$ a test string"
|
文字位置offsetから始まる長さlen文字の一部文字列をリターンします。
オフセット位置の番号は1から開始されます。offsetが負の場合は、抽出開始位置は文字列の終端からのオフセットで数えられます。
lenが省略された場合、一部文字列はSの終端まで拡張されます。lenに負の値を指定すると、文字列の最後のlen文字が抽出されます。
例:
substr ("This is a test string", 6, 9)
⇒ "is a test"
substr ("This is a test string", -11)
⇒ "test string"
substr ("This is a test string", -11, -7)
⇒ "test"
|
この関数はPerlの同名の関数を元にしています。
文字列をマッチングするための正規表現です。strからpatを検索して、マッチした位置と部分文字列、マッチしなかったときは空の値をリターンします。
マッチさせるパターンpatには以下の標準的なregex演算子が含まれます:
.任意の文字にマッチする
* + ? {}繰り返し演算子。以下の意味をもつ
*0回以上のマッチ
+1回以上のマッチ
?0または1回のマッチ
{n}正確にn回のマッチ
{n,}n回以上のマッチ
{m,n}m回からn回のマッチ
[…] [^…]リスト演算子。パターンは"["と"]"の間にリストされた任意の文字にマッチする。最初の文字が"^"の場合、パターンの意味は逆になり、角カッコの間にリストされた文字以外の任意の文字にマッチする。
リスト演算子内で以下で定義されるエスケープシーケンスを使用できる。たとえば浮動小数点数にたいするテンプレートは[-+.\d]+のようになる。
() (?:)グループ化演算子。1つ目の丸カッコだけの形式はトークンも作成する。
|選択肢のための演算子。正規表現からなる選択肢の1つにマッチする。選択肢は上述のグループ化演算子()で区切らなければならない。
^ $アンカー演算子。文字列の開始、または終了を示すには、(^)および($)のパターンが要求される。
さらに以下のエスケープシーケンスは、特別な意味をもつ。
\d任意の数字にマッチする
\D数字以外の任意の文字にマッチする
\s任意の空白文字にマッチする
\S空白文字以外の任意の文字にマッチする
\w任意の単語文字にマッチする
\W単語以外の任意の文字にマッチする
\<単語の先頭にマッチする
\>単語の末尾にマッチする
\B単語の内部にマッチする
実装ノート: MATLABとの互換性のため、通常のエスケープシーケンス(例: "n" =>
newline)は、patがシングルクォートで定義されているか否かに関わらず処理されます。エスケープシーケンスの補間を停止するには2つ目のバックスラッシュ(例:
"\\n")を使うか、regexptranslate関数を使用してください。
regexpのデフォルトの出力順は以下で与えられます
マッチした部分文字列の開始インデクス
マッチした部分文字列の終了インデクス
マッチした各トークンをpat内の(…)で囲んだものの範囲
各マッチのテキストのセル配列
各マッチのトークンのテキストのセル配列
マッチした名前付きトークン(名前はフィールド名として使用される)のテキストを含む構造体。名前付きトークンは(?<name>…)で表される。
テキストのセル配列(例: patにより文字列を分割したときの残り)はマッチによりリターンされない。
特定の出力引数、または出力引数の順番は、追加の引数optで選択できます。これらは文字列で、出力引数とオプション引数の対応は以下のとおりです
'start' | s | ||
'end' | e | ||
'tokenExtents' | te | ||
'match' | m | ||
'tokens' | t | ||
'names' | nm | ||
'split' | sp |
追加の引数を以下に要約します。
パターンの最初の出現だけをリターンする。
大文字小文字を区別せずにマッチングする(デフォルト)。
パターン内で(?-i)を使用して代替できる。
大文字小文字を区別してマッチングする。
パターン内で(?i)を使用して代替できる。
アンカー文字は文字列の開始と終了にマッチする(デフォルト)。
パターン内で(?-m)を使用して代替できる。
アンカー文字は行の開始と終了にマッチする(デフォルト)。
パターン内で(?m)を使用して代替できる。
パターン.は、改行文字を含むすべての文字にマッチする(デフォルト)。
パターン内で(?s)を使用して代替できる。
パターン.は、改行文字を除くすべての文字にマッチする。
パターン内で(?-s)を使用して代替できる。
空白文字を含む、パターン内のすべての文字は有意であり、パターンマッチングに使用される(デフォルト)。
パターン内で(?-x)を使用して代替できる。
パターンは任意の空白文字、および文字‘#’で始まるコメントを含むことができる。
パターン内で(?x)を使用して代替できる。
長さ0のマッチはリターンされない(デフォルト)。
長さ0のマッチをリターンする。
regexp ('a', 'b*', 'emptymatch')は[1
2]をリターンする。それは0文字以上の'b'が位置1と文字列終端にマッチするからである。
大文字小文字を区別せずに正規表現による文字列マッチングを行います。str内からpatを検索して、マッチした位置と部分文字列、マッチしなかったときは空の値をリターンします。検索パターン構文の詳細は、regexpを参照してください。
See also: regexp.
string内に存在するパターンpatを、repstrで置き換えます。
パターンはregexpに記述されている正規表現です。regexpを参照してください。
置換文字列には$iを含めることができます。これはマッチした文字列内の、i番目のカッコで括られたもので置換されます。たとえば、
regexprep ("Bill Dunn", '(\w+) (\w+)', '$2, $1')
|
は、"Dunn, Bill"をリターンします
追加オプションはregexpのものに以下が加わります
結果の中の最初にあったregexpだけを置換する。
このオプションは互換性のためだけで、無視される。
実装ノート: MATLABとの互換性のためpatとrepstr内のエスケープシーケンス(例: "n"
=>
改行)は、それらがシングルクォート内で定義されているか否かに関わらず、通常どおり処理されます。エスケープシーケンスの補間を防ぐには2つ目のバックスラッシュを使かう(例:
"\\n")か、regexptranslate関数を使用してください。
正規表現として使用するために文字列を翻訳します。これにはワイルドカードの置換や、特殊文字のエスケープが含まれます。この振る舞いはopにより制御され、以下の値をとることができます
"wildcard"ワイルドカード文字.、*、?は適切な正規表現に置き換えられます。たとえば:
regexptranslate ("wildcard", "*.m")
⇒ ".*\.m"
|
"escape"文字$.?[]は正規表現では特別な意味をもつので、リテラルとして扱うためには、エスケープする必要があります。たとえば:
regexptranslate ("escape", "12.5")
⇒ "12\.5"
|
t内のTAB文字を、スペースで置き換えます。TAB幅はtwでの指定、またはデフォルトの8になります。入力のtは2次元文字配列、または文字列のセル配列です。出力は入力と同じクラスになります。
オプション引数deblankがtrueの場合、文字データの末尾のスペースは削除されます。
以下は、ファイルを読み込んでから、最後のス同じファイルのスペースを取り除いた、TABなしバージョンを書き込む例です。
fid = fopen ("tabbed_script.m");
text = char (fread (fid, "uchar")');
fclose (fid);
fid = fopen ("untabified_script.m", "w");
text = untabify (strsplit (text, "\n"), 8, true);
fprintf (fid, "%s\n", text{:});
fclose (fid);
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveは文字列と数値の間で、さまざまな種類の変換をサポートします。1例をあげると、16進数を含む文字列を、浮動小数点数に変換することができます。
hex2dec ("FF")
⇒ 255
|
文字列sで表された2進数に対応する10進数をリターンします。たとえば:
bin2dec ("1110")
⇒ 14
|
変換において、2進数値のかどくせいを工場させるために使用されるかもしれないスペースは無視されます。
bin2dec ("1000 0001")
⇒ 129
|
sが文字列マトリクスの場合は、sの行ごとに1つの数値に変換した列ベクターをリターンします。無効な行はNaNに評価されます。
sが文字列のセル配列の場合は、s内のセル要素ごとに1つの数値に変換した列ベクターをリターンします。
非負の整数dに大王する2進数値を、1と0からなる文字列でリターンします。たとえば:
dec2bin (14)
⇒ "1110"
|
dがマトリクスまたはセル配列の場合は、d内の要素ごとに1行(最大値の幅になるように先頭に0がパディングされます)となる文字列マトリクスをリターンします。
2つ目のオプション引数lenは、結果の最小の桁数を指定します。
非負の整数dに対応する16進文字列をリターンします。たとえば:
dec2hex (2748)
⇒ "ABC"
|
dがマトリクスまたはセル配列の場合は、d内の要素ごとに1行(最大値の幅になるように先頭に0がパディングされます)となる文字列マトリクスをリターンします。
2つ目のオプション引数lenは、結果の最小の桁数を指定します。
文字列sで表された16進数値に対応する整数をリターンします。たとえば:
hex2dec ("12B")
⇒ 299
hex2dec ("12b")
⇒ 299
|
sが文字列マトリクスの場合は、sの行ごとに1つの数値に変換した列ベクターをリターンします。無効な行はNaNに評価されます。
sがセル配列の場合は、s内のセル要素ごとに1つの数値に変換された列ベクターをリターンします。
非負の整数dに対応する、基数baseのシンボル文字列をリターンします。
dec2base (123, 3) ⇒ "11120" |
dがマトリクスまたはセル配列の場合は、d内の要素ごとに1行(最大値の幅になるように先頭に0がパディングされます)となる文字列マトリクスをリターンします。
baseが文字列の場合は、baseの文字がdの桁のシンボルとして使用されます。スペース(’ ’)はシンボルとして使用されません。
dec2base (123, "aei") ⇒ "eeeia" |
3つ目のオプション引数lenは、結果の最小の桁数を指定します。
基数baseの数字文字列を10進整数(基数10)に変換します。
base2dec ("11120", 3)
⇒ 123
|
sが文字列マトリクスの場合は、sの各行が1つの値になる列ベクターをリターンします。行に無効なシンボルが含まれる場合、対応する値はNaNになります。
sが文字列のセル配列の場合は、s内のセル要素ごとに1つの値となる列ベクターをリターンします。
baseが文字列の場合は、baseの文字がsの数字のシンボルとして使用されます。スペース(’ ’)はシンボルとして使用されません。
base2dec ("yyyzx", "xyz")
⇒ 123
|
倍精度または単精度数値のベクターを、IEEE 754数値表現の8文字または16文字の16進文字列に型キャストします。たとえば:
num2hex ([-1, 1, e, Inf])
⇒ "bff0000000000000
3ff0000000000000
4005bf0a8b145769
7ff0000000000000"
|
引数nが単精度数値の数値またはベクターの場合、リターンされる文字列の長さは8になります。たとえば:
num2hex (single ([-1, 1, e, Inf]))
⇒ "bf800000
3f800000
402df854
7f800000"
|
16文字16進文字列を、IEEE
754の倍精度数値に型キャストします。与えられた文字列が16文字未満の場合は、右に文字'0'がパディングされます。
文字列マトリクスが与えられた場合、hex2numは各行を個別の数値として扱います。
hex2num (["4005bf0a8b145769"; "4024000000000000"]) ⇒ [2.7183; 10.000] |
オプション引数classにはもっと"single"を渡すことができ、これは与えられた文字列を単精度数値として解釈すべきことを指定します。この場合、sは8文字の16進文字列になります。たとえば:
hex2num (["402df854"; "41200000"], "single") ⇒ [2.7183; 10.000] |
文字列を実数または複素数に変換します。
文字列は以下のフォーマットのうちの1つでなければなりません。ここでaとbは実数、複素数単位は'i'と'j'です。
もし与えられた場合、aおよび/またはbは[+-]d[,.]d[[eE][+-]d]という形式です。ここで角カッコはオプション引数を示し、'd'は0以上の数字を示します。特別な入力値Inf、NaN、NAも指定できます。
sは文字列、文字マトリクス、またはセル配列です。文字列配列にたいしては、各行にたいして変換が繰り返され、倍精度または複素数の配列がリターンされます。s内の空行は削除され、数値配列はリターンされません。セル配列にたいしては各文字列要素が処理され、sと同じ次元の倍精度または複素数の配列がリターンされます。
互換性のないスカラーまたは文字列が入力された場合、str2doubleはNaNをリターンします。同様に文字配列が入力された場合、str2doubleは変換できなかったsの行にNaNをリターンします。セル配列にたいして、str2doubleは変換がに失敗したsの要素にたいしてNaNをリターンします。文字列と数値が混交されたセル配列内の数値要素は文字列ではないので、これらの要素の変換は失敗しNaNがリターンされることに注意してください。
str2doubleはstr2numに置き換えることができ、未知のデータにたいしてevalを使用するセキュリティリスクを避けます。
See also: str2num.
pos("left"、"center"、または"right")に応じてsを整列したテキストをリターンします。posが省略された場合、デフォルトは"right"です。
null文字はスペースに置き換えられます。それ以外のすべての文字は、非空白文字として扱います。
例:
strjust (["a"; "ab"; "abc"; "abcd"])
⇒
" a"
" ab"
" abc"
"abcd"
|
文字列(または文字配列)sを数値(または配列)に変換します。たとえば:
str2num ("3.141596")
⇒ 3.141596
str2num (["1, 2, 3"; "4, 5, 6"])
⇒ 1 2 3
4 5 6
|
2つ目のオプション出力stateは、変換が成功したときは論理的trueになります。変換が失敗した場合、数値出力は空で、stateはfalseになります。
警告:
str2numは変換を行うためにeval関数を使用しているので、文字列sに含まれる任意のコードは実行されます。より安全かつ高速な変換のためにstr2doubleを使用してください。
文字列のセル配列には、str2doubleを使用してください。
See also: str2double, eval.
sのASCII表現をマトリクスでリターンします。たとえば:
toascii ("ASCII")
⇒ [ 65, 83, 67, 73, 73 ]
|
See also: char.
文字列またはセル文字列sの大文字を対応する小文字に置き換えたコピーをリターンします。非アルファベット文字は変更されません。たとえば:
tolower ("MiXeD cAsE 123")
⇒ "mixed case 123"
|
See also: toupper.
文字列またはセル文字列sの小文字を対応する大文字に置き換えたコピーをリターンします。非アルファベット文字は変更されません。たとえば:
toupper ("MiXeD cAsE 123")
⇒ "MIXED CASE 123"
|
See also: tolower.
string内のエスケープされた特殊文字を、特殊文字にに変換します。
文字列内の特殊文字を、エスケープされた形式に変換します。たとえば、
bell = "\a"; |
この式は変数bellにalert文字(control-g、ASCIIコード7)を割り当てます。この文字列がプリントされた場合、(もし可能なら)システムは端末ベルを鳴らすでしょう。通常これは望んだ結果です。しかし特殊文字をエスケープシーケンスに置き換えて、元の文字列表現をプリントできたほうが便利な場合もあります。たとえば、
octave:13> undo_string_escapes (bell) ans = \a |
これはプリントできないalert文字を、プリント可能な表現に置き換えます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveは以下のような、C標準ライブラリーに倣った文字クラステスト関数も提供します。これらはすべて文字列配列を処理して、0と1からなるマトリクスをリターンします。非0の要素は文字列配列内の対応する文字がtrueであることを示します。たとえば:
isalpha ("!Q@WERT^Y&")
⇒ [ 0, 1, 0, 1, 1, 1, 1, 0, 1, 0 ]
|
sの要素が英数字ならtrue、それ以外はfalseのような論理配列をリターンします。この関数は(isalpha
(s) | isdigit (s))と等価です。
sの要素がアルファベットならtrue、それ以外はfalseのような論理配列をリターンします。この関数は(islower
(s) | isupper (s))と等価です。
See also: isdigit, ispunct, isspace, iscntrl, isalnum, islower, isupper.
sの要素がアルファベットならtrue、それ以外はfalseのような論理配列をリターンします。この関数はisalpha関数のエイリアスです。
See also: isalpha, isdigit, ispunct, isspace, iscntrl, isalnum.
sの要素がアルファベット小文字ならtrue、それ以外はfalseのような論理配列をリターンします。
sの要素がアルファベット大文字ならtrue、それ以外はfalseのような論理配列をリターンします。
sの要素が10進数字(0-9)ならtrue、それ以外はfalseのような論理配列をリターンします。
See also: isxdigit, isalpha, isletter, ispunct, isspace, iscntrl.
sの要素が16進数字(0-9およびa-fA-F)ならtrueのような論理配列をリターンします。
See also: isdigit.
sの要素が句読点文字ならtrue、それ以外はfalseのような論理配列をリターンします。
sの要素が空白文字(スペース、改ページ、改行、復帰、タブ、垂直タブ)ならtrue、それ以外はfalseのような論理配列をリターンします。
sの要素がコントロール文字ならtrue、それ以外はfalseのような論理配列をリターンします。
sの要素がプリント可能文字(ただしスペース以外)ならtrue、それ以外はfalseのような論理配列をリターンします。
See also: isprint.
sの要素がプリント可能文字(スペース文字も含む)ならtrue、それ以外はfalseのような論理配列をリターンします。
See also: isgraph.
sの要素がASCII文字(10進の0から127)ならtrue、それ以外はfalseのような論理配列をリターンします。
文字列プロパティをテストします。たとえば:
isstrprop ("abc123", "alpha")
⇒ [1, 1, 1, 0, 0, 0]
|
strがセル配列の場合は、セル配列の各要素にたいしてisstrpopが再帰的に適用されます。
数値配列は文字列に変換されます。
2つ目の引数propは、以下のうちの1つでなければなりません
"alpha"文字がアルファベットならtrue。
"alnum""alphanum"文字が英数字ならtrue。
"lower"アルファベット小文字ならtrue。
"upper"アルファベット大文字ならtrue。
"digit"10進数字(0-9)ならtrue。
"xdigit"16進数字(a-fA-F0-9)ならtrue。
"space""wspace"空白文字(スペース、改ページ、改行、復帰、タブ、垂直タブ)ならtrue。
"punct"句読点文字(スペース、英数字を除くプリント文字)ならtrue。
"cntrl"コントロール文字ならtrue。
"graph""graphic"スペース以外のプリント文字ならtrue。
"print"スペースを含むプリント文字ならtrue。
"ascii"ASCIIエンコーディング範囲内の文字ならtrue。
See also: isalpha, isalnum, islower, isupper, isdigit, isxdigit, isspace, ispunct, iscntrl, isgraph, isprint, isascii.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveには、任意のデータ型を同じ変数に含めるために、2つの異なるメカニズムをサポートします。Cスタイルの構造体は名前付きフィールドでインデクスされ、セル配列は配列の各要素が異なるデータ型と形状をもつことができます。関数の複数の入力引数やリターン値は、カンマ区切りリストという他のデータ型により形成されます。
| 6.1 Structures | ||
| 6.2 Cell Arrays | ||
| 6.3 Comma Separated Lists |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octaveには構造体内のデータを組織化するためのサポートが含まれます。現在の実装は文字列によるインデクスに限定された連想配列を使用しますが、Cスタイルの構造体に類似した構文です。
| 6.1.1 Basic Usage and Examples | ||
| 6.1.2 Structure Arrays | ||
| 6.1.3 Creating Structures | ||
| 6.1.4 Manipulating Structures | ||
| 6.1.5 Processing Data in Structures |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
以下はOctaveでデータ構造体を使用する例です。
構造体の要素には任意の値型を使用できます。たとえば
x.a = 1; x.b = [1, 2; 3, 4]; x.c = "string"; |
この3つの式は、要素が3つの構造体を作成します。文字‘.’は構造体名とィールド名を区別し、Octaveにたいしてこれが構造体であることを示します。他の変数と同様に構造体の名前をタイプすれば、構造体の値をプリントできます。
x
⇒ x =
{
a = 1
b =
1 2
3 4
c = string
}
|
Octaveは任意の順序で要素をプリントすることに注意してください。
他の変数と同じように、構造体をコピーできます。
y = x
⇒ y =
{
a = 1
b =
1 2
3 4
c = string
}
|
構造体はそれ自体が値なので、構造体の要素が他の構造体を参照することもあります。以下の命令文は構造体xの要素bの値を、値が3であるような1つの要素dをもつデータ構造体に変更します。
x.b.d = 3;
x.b
⇒ ans =
{
d = 3
}
x
⇒ x =
{
a = 1
b =
{
d = 3
}
c = string
}
|
構造体が他の構造体を含むとき、Octaveはそれらの2、3レベルだけをプリントすることに注意してください。たとえば:
a.b.c.d.e = 1;
a
⇒ a =
{
b =
{
c =
{
1x1 struct array containing the fields:
d: 1x1 struct
}
}
}
|
これは、大きくネストが深い構造体による、長く混乱した出力を抑制するためです。ネストされた構造体にたいしてプリントするレベル数は、関数struct_levels_to_printでセットすることができ、構造体配列の内容のプリントを有効にするには関数print_struct_array_contentsが使用されます。
表示する構造体レベル数を指定する内部変数にたいして、問い合わせまたはセットをします。
関数の内部で"local"オプションとともに呼び出された場合、変数の変更はその関数および関数のサブルーチンにたいしてローカルになります。関数をexitするとき、変数の元の値がリストアされます。
See also: print_struct_array_contents.
構造体配列の内容をプリントするかどうかを指定する内部変数にたいして、問い合わせまたはセットを行います。
trueの場合、構造体配列の要素はプリントされます。この変数は、要素が常にプリントされるスカラー構造体には影響しません。しかしどちらの場合も、プリントされるのはstruct_levels_to_printで指定されるレベル数に制限されます。
関数の内部で"local"とともに呼び出された場合、変数の変更はその関数および関数のサブルーチンにたいしてローカルになります。関数をexitするときに、変数の元の値がリストアされます。
See also: struct_levels_to_print.
関数は構造体をリターンすることができます。たとえば、以下の関数はマトリクスの実数部と複素部を分割して、同じ構造体変数の2つの要素に格納します。
function y = f (x) y.re = real (x); y.im = imag (x); endfunction |
複素数値を引数に呼び出された場合、fは元の関数引数の実数部と虚数部を含むデータ構造体をリターンします。
f (rand (2) + rand (2) * I)
⇒ ans =
{
im =
0.26475 0.14828
0.18436 0.83669
re =
0.040239 0.242160
0.238081 0.402523
}
|
リストをリターンする関数には構造体要素を含めることができ、それらは他の変数と同じようにインデクスされます。たとえば:
[ x.u, x.s(2:3,2:3), x.v ] = svd ([1, 2; 3, 4]);
x
⇒ x =
{
u =
-0.40455 -0.91451
-0.91451 0.40455
s =
0.00000 0.00000 0.00000
0.00000 5.46499 0.00000
0.00000 0.00000 0.36597
v =
-0.57605 0.81742
-0.81742 -0.57605
}
|
for命令の特別フォームを使用して、構造体のすべての要素を巡回することも可能です(Looping Over Structure Elementsを参照)。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
構造体配列とは、構造体の各フィールドがセル配列で表される、構造体固有のインスタンスです。 これらの各セル配列は同じ次元をもちます。概念上、構造体配列は同じフィールドをもつ構造体の配列と捉えることもできます。以下は構造体配列を作成する例です
x(1).a = "string1"; x(2).a = "string2"; x(1).b = 1; x(2).b = 2; |
これは2つのフィールドをもつ2×1の構造体配列を作成しています。構造体配列を作成する別の方法として、struct関数があります(Creating Structuresを参照)。すでに示したように、名前をタイプすることにより、構造体配列の値をプリントできます。
x
⇒ x =
{
1x2 struct array containing the fields:
a
b
}
|
構造体配列の各要素はx(1)のようにインデクス付された変数でリターンされ、この変数は2つのフィールドをもつ構造体をリターンします:
x(1)
⇒ ans =
{
a = string1
b = 1
}
|
さらに構造体配列は、それがフィールド名でインデクス付けされている場合は、フィールド値のカンマ区切りリストをリターンします(Comma Separated Listsを参照)。
x.a
⇒
ans = string1
ans = string2
|
以下は、このカンマ区切りリストを割り当ての左辺で使用する例です。
[x.a] = deal ("new string1", "new string2");
x(1).a
⇒ ans = new string1
x(2).a
⇒ ans = new string2
|
数値配列に限られますが、インデクスにベクターを使用できます(Index Expressionsを参照):
x(3:4) = x(1:2);
[x([1,3]).a] = deal ("other string1", "other string2");
x.a
⇒
ans = other string1
ans = new string2
ans = other string2
ans = new string2
|
関数sizeは構造体のサイズをリターンします。上記の例にたいしては以下のようになります
size (x)
⇒ ans =
1 4
|
構造体配列の要素は、要素に空マトリクスを割り当てることにより、数値配列と同様のやり方で削除できます。たとえば
in = struct ("call1", {x, Inf, "last"},
"call2", {x, Inf, "first"})
⇒ in =
{
1x3 struct array containing the fields:
call1
call2
}
in(1) = [];
in.call1
⇒
ans = Inf
ans = last
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
インデクス演算子"."とは別に、octaveでは動的名前付け"(var)"、またはstructを使用して構造体を作成できます。動的名前付けでは、変数の文字列値をフィールド名に使用します。たとえば:
a = "field2";
x.a = 1;
x.(a) = 2;
x
⇒ x =
{
a = 1
field2 = 2
}
|
動的インデクス付けでは、Octaveで有効な識別子だけでなく、任意の文字列を使用できます(これはMATLABでは機能しないことに注意してください):
a = "long field with spaces (and funny char$)";
x.a = 1;
x.(a) = 2;
x
⇒ x =
{
a = 1
long field with spaces (and funny char$) = 2
}
|
警告IDのOctave:matlab-incompatibleによい、この使用についての警告を有効にできます。warning_idsを参照してください。
実際には、データ構造体の正確なフィールド名を構築するときに、文字列を操作するすべての関数を使用できます。
names = ["Bill"; "Mary"; "John"];
ages = [37; 26; 31];
for i = 1:rows (names)
database.(names(i,:)) = ages(i);
endfor
database
⇒ database =
{
Bill = 37
Mary = 26
John = 31
}
|
構造体を作成する3つ目の方法は、structコマンドです。structは1対の引数をとります。1つ目の引数は構造体内に含めるためのfieldnameで、2つ目はスカラーまたはセル配列です。たとえば:
struct ("field1", 1, "field2", 2)
⇒ ans =
{
field1 = 1
field2 = 2
}
|
structにスカラーとセル配列が混交された値が渡された場合は、矛盾しない次元の構造体配列を作成するようにスカラー引数が展開されます。たとえば:
s = struct ("field1", {1, "one"}, "field2", {2, "two"},
"field3", 3);
s.field1
⇒
ans = 1
ans = one
s.field2
⇒
ans = 2
ans = two
s.field3
⇒
ans = 3
ans = 3
|
セル配列を特定のフィールドに含む構造体を作成したい場合は、以下の例のようにそれを別のセル配列でラップしなければなりません:
struct ("field1", {{1, "one"}}, "field2", 2)
⇒ ans =
{
field1 =
{
[1,1] = 1
[1,2] = one
}
field2 = 2
}
|
スカラーまたは配列の構造体を作成して、値を初期化します。変数field1、field2、…はフィールド名を指定する文字列で、変数value1、value2、…には任意の型を使用できます。
値がセル配列の場合は構造体配列を作成して、値を初期化します。値となる各セル配列の次元は一致していなければなりません。シングルトンのセルおよび非セル値は、配列全体を満たすように繰り返されます。セルが空の場合は、指定されたフィールド名の空の構造体配列が作成されます。
引数がオブジェクトの場合は、それにもとづいた構造体をリターンします。
構文が構造体配列に最適化されていることに注目してください。以下の例で考えてみましょう:
struct ("foo", 1)
⇒ scalar structure containing the fields:
foo = 1
struct ("foo", {})
⇒ 0x0 struct array containing the fields:
foo
struct ("foo", { {} })
⇒ scalar structure containing the fields:
foo = {}(0x0)
struct ("foo", {1, 2, 3})
⇒ 1x3 struct array containing the fields:
foo
|
1つ目は通常のスカラー構造体で、1つのフィールドと1つの値をもちます。2つ目は値をもたない1つのフィールドをもつ、空の構造体配列を作成します。値が1つのエントリーを含むセル配列の場合は、そのフィールドの値が単一のエントリーとなるようなスカラー構造体になります。そのような単一のエントリーは、空のセル配列にたいして発生します。
最後に値が非スカラーのセル配列の場合、structは構造体配列を作成します。
See also: cell2struct, fieldnames, orderfields, getfield, setfield, rmfield, structfun.
オブジェクトが構造体または構造体配列かをテストするのに、関数isstructを使用してできます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
以下は、構造体のフィールドを操作する関数です。
構造体sのフィールド数をリターンします。
See also: fieldnames.
入力で指定されたフィールド名により、文字列のセル配列をリターンします。
入力が構造体structの場合、構造体の要素が名前になります。
入力がOctaveオブジェクトobjの場合、オブジェクトのパブリックプロパティが名前になります。
入力がJavaオブジェクトjavaobj、またはJavaクラス名jclassnameの場合、オブジェクトまたはクラスのパブリックなデータ要素が名前になります。
See also: nfields, isfield, orderfields, struct, methods.
xが構造体でnameという名前の要素を含む場合は、trueをリターンします。nameが文字列のセル配列の場合は、等しい次元の論理配列をリターンします。
See also: fieldnames.
構造体sのフィールドメンバーfieldを、valにセットします。たとえば:
s = struct (); s = setfield (s, "foo bar", 42); |
これは以下と等価です
s.("foo bar") = 42;
|
フィールド名は有効なOctave識別子ではないので、ここでは通常の構造体構文s.foo bar =
42は使用できないことに注意してください。フィールド名に任意の文字列を使用するのはMATLABと互換性がないので、Octave:matlab-incompatible警告がセットされている場合はこの使用にたいして警告されるでしょう。XREFwarning_idsを参照してください。
2つ目の呼び出し形式では、構造体配列のフィールドへのセットはインデクスidx1、idx2、…とフィールドfield1, field2, …のように連続してネストされているかもしれません。インデクスは、そのネスト深さでの期待されるインデクスを含むセルでなければなりません。
したがって以下のように考えることができます
s = struct ("baz", 42);
setfield (s, {1}, "foo", {1}, "bar", 5)
⇒ ans =
scalar structure containing the fields:
baz = 42
foo =
scalar structure containing the fields:
bar = 5
|
ここでは最初に通常の構造体配列のフィールドbazに42をセットしています。それから一意なインデクスを含む単独セル2つによりインデクス付けされる、別のネストされたスカラー構造体フィールドに値をセットしています。
最後は、ネストされた構造体配列の例です
sa.foo = 1;
sa = setfield (sa, {2}, "bar", {3}, "baz", 6);
sa(2).bar(3)
⇒ ans =
scalar structure containing the fields:
baz = 6
|
ここではsaは構造体配列で、要素1がフィールドfdで、2つ目のフィールドは3つ目の要素が構造体であるような別の構造体配列です
以下のようにして、上記の例と同じ結果を得られることに注意してください:
SA.foo = 1; SA(2).bar(3).baz = 6 |
See also: getfield, rmfield, isfield, fieldnames, isstruct, struct.
構造体(またはネストされた構造体)からフィールドを抽出します。構文はsetfieldと同様ですが、最後のvalがなく、値をセットするかわりに、値をリターンする点が異なります。
See also: setfield, rmfield, isfield, fieldnames, isstruct, struct.
構造体(または構造体配列)sからフィールドfを削除したコピーをリターンします。fが文字列のセル配列か文字配列の場合は、それぞれの名前付きフィールドを削除します。
See also: orderfields, fieldnames.
アルファベット順、またはs2で指定された順にフィールドを整列したs1のコピーをリターンします。
1つの構造体が与えられた場合は、s1のフィールド名をアルファベット順に整列します。
2つ目の引数が構造体の場合は、s1のフィールド名をs2に出現する順に整列します。2つ目の引数には順序を指定する置換ベクター(permutation vector)、または望む順に整列されたs1内のフィールド名を含む文字列のセル配列を指定することもできます。
2つ目のオプション出力引数pには、元の名前順を新しい名前順に変換する置換ベクターが割り当てられます。
例:
s = struct ("d", 4, "b", 2, "a", 1, "c", 3);
t1 = orderfields (s)
⇒ t1 =
{
a = 1
b = 2
c = 3
d = 4
}
t = struct ("d", {}, "c", {}, "b", {}, "a", {});
t2 = orderfields (s, t)
⇒ t2 =
{
d = 4
c = 3
b = 2
a = 1
}
t3 = orderfields (s, [3, 2, 4, 1])
⇒ t3 =
{
a = 1
b = 2
c = 3
d = 4
}
[t4, p] = orderfields (s, {"d", "c", "b", "a"})
⇒ t4 =
{
d = 4
c = 3
b = 2
a = 1
}
p =
1
4
2
3
|
See also: getfield, rmfield, isfield, isstruct, fieldnames, struct.
subsrefおよびsubsasgnで使用するための添字構造体(subscript
structure)を作成します。たとえば:
idx = substruct ("()", {3, ":"})
⇒
idx =
{
type = ()
subs =
{
[1,1] = 3
[1,2] = :
}
}
x = [1, 2, 3; 4, 5, 6; 7, 8, 9];
subsref (x, idx)
⇒ 7 8 9
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
構造体内のデータを処理するには、forループを使用するのが一番シンプルな方法です(Looping Over Structure Elementsを参照)。構造体の各フィールドにユーザー定義関数を適用するstructfun関数でも、同様の効果を得ることができます。structfunを参照してください。
かわりに、構造体内のデータを処理するために、処理の前に構造体を他のコンテナー型に変換すると良いかもしれません。
構造体オブジェクトに格納されたオブジェクトから、新たなセル配列を作成します。fが構造体内のフィールド数の場合、結果となるセル配列は[f
size(s)]に応じた次元のベクターとなります。たとえば:
s = struct ("name", {"Peter", "Hannah", "Robert"},
"age", {23, 16, 3});
c = struct2cell (s)
⇒ c = {2x1x3 Cell Array}
c(1,1,:)(:)
⇒
{
[1,1] = Peter
[2,1] = Hannah
[3,1] = Robert
}
c(2,1,:)(:)
⇒
{
[1,1] = 23
[2,1] = 16
[3,1] = 3
}
|
See also: cell2struct, fieldnames.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
複数の異なるサイズや型の変数を、1つの変数に格納するのが必要だったり便利なことがあるかもしれません。セル配列はまさにそれを行うことを可能にするコンテナークラスです。一般的にセル配列はN次元配列と同様に機能しますが、割り当てとインデクスの演算子に‘{’と‘}’を使用する点が異なります。
| 6.2.1 Basic Usage of Cell Arrays | ||
| 6.2.2 Creating Cell Arrays | ||
| 6.2.3 Indexing Cell Arrays | ||
| 6.2.4 Cell Arrays of Strings | ||
| 6.2.5 Processing Data in Cell Arrays |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
以下は文字列と2行2列の乱数行列を含むセル配列を作成するコードの例です
c = {"a string", rand(2, 2)};
|
セル配列の要素にアクセスするために、{および}演算子でインデクス付けすることができます。したがって上記の例で作成された変数は、以下のようにインデクス付けできます:
c{1}
⇒ ans = a string
|
数値配列と同様に、セル配列の複数の要素をインデクス用ベクターでインデクス付けして抽出できます。
c{1:2}
⇒ ans = a string
⇒ ans =
0.593993 0.627732
0.377037 0.033643
|
インデクス演算子はセル配列に要素を挿入したり上書きするためにも使用できます。以下のコードでは、上記で作成したセル配列の3番目にスカラーの3を挿入しています
c{3} = 3
⇒ c =
{
[1,1] = a string
[1,2] =
0.593993 0.627732
0.377037 0.033643
[1,3] = 3
}
|
セル配列のインデクス操作についての詳細はIndexing Cell Arraysを参照してください。
前の例のように、一般的にネストされたセル配列は階層的に表示されます。それらをインデクスにより参照するほうが理解しやすい場合は、celldisp関数を使用できます。
セル配列の内容を再帰的に表示します。デフォルトでは、値は変数cの名前とともに表示されます。しかし、この名前は変数nameで置き換えることができます。たとえば:
c = {1, 2, {31, 32}};
celldisp (c, "b")
⇒
b{1} =
1
b{2} =
2
b{3}{1} =
31
b{3}{2} =
32
|
See also: disp.
オブジェクトがセル配列かどうかテストするには、iscell関数を使用します。たとえば:
iscell (c)
⇒ ans = 1
iscell (3)
⇒ ans = 0
|
xがセル配列の場合は、trueをリターンします。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
冒頭に紹介した例(Basic Usage of Cell Arraysを参照)では、現在利用可能な変数を含むセル配列を作成する方法を示しました。しかし、セル配列を作成した後にデータをセットするほうが便利な場合も多いでしょう。
cell関数は与えられたサイズの空マトリクスを含むセル配列をリターンします。この関数は、新たに数値配列を作成するzeros関数に似ています。以下は空マトリクスを含む2行2列のセル配列を作成する例です
c = cell (2,2)
⇒ c =
{
[1,1] = [](0x0)
[2,1] = [](0x0)
[1,2] = [](0x0)
[2,2] = [](0x0)
}
|
数値配列と同様に、セル配列を多次元にすることもできます。cell関数hqリターンされるセル配列のサイズを決定するために、任意の個数の正の整数を受け入れます。正の整数のベクターによりセル配列のサイズをセットすることもできます。以下の例では、サイズの等しい2つのセル配列を作成して、1つ目のセル配列にサイズを表示しています
c1 = cell (3, 4, 5);
c2 = cell ( [3, 4, 5] );
size (c1)
⇒ ans =
3 4 5
|
これまで見てきたように、size関数はセル配列にたいしても機能します。length、numel、rows、columnsのようなサイズを報告する他の関数も同様に機能します。
新たにセル配列オブジェクトを作成します。
1つのスカラー整数引数とともに呼び出された場合は、NxNの正方セル配列をリターンします。2つ以上のスカラー整数引数、または整数値ベクターとともに呼び出された場合は、与えられた次元の配列をリターンします。
See also: cellstr, mat2cell, num2cell, struct2cell.
空のセル配列を作成してから値をセットする別の方法としてnum2cell、mat2cell、cellslices関数を使用して数値配列をセル配列に変換する方法が利用できます。
数値マトリクスAをセル配列に変換します。dimが定義されている場合は、Cがこの次元での次元1となり、Aの要素はCにスライスとして配されます。たとえば:
num2cell ([1,2;3,4])
⇒
{
[1,1] = 1
[2,1] = 3
[1,2] = 2
[2,2] = 4
}
num2cell ([1,2;3,4],1)
⇒
{
[1,1] =
1
3
[1,2] =
2
4
}
|
See also: mat2cell.
マトリクスAをセル配列に変換します。Aが2次元の場合、sum (m) == size (A,
1)とsum (n) == size (A,
2)が成り立つ必要があります。同様にAが多次元で次元数の引数がAの次元と等しい場合は、sum (di)
== size (A, i)が成り立つ必要があります。
単一の次元引数rが与えられた場合、他の次元引数はsize (A,i)と等しいとみなされます。
以下はmat2cellを使用する例です
mat2cell (reshape (1:16,4,4), [3,1], [3,1])
⇒
{
[1,1] =
1 5 9
2 6 10
3 7 11
[2,1] =
4 8 12
[1,2] =
13
14
15
[2,2] = 16
}
|
与えられた配列xにたいして、この関数はインデクスベクターlbおよびub(下限と上限を指定)から決定される配列スライスのセル配列を生成します。言い換えると、これは以下のコードと等価です:
n = length (lb);
sl = cell (1, n);
for i = 1:length (lb)
sl{i} = x(:,…,lb(i):ub(i),…,:);
endfor
|
インデクスの位置はdimにより決定されます。指定されなかった場合は、最初の非シングルトン次元に沿ってスライシングが行われます。
See also: cell2mat, cellindexmat, cellfun.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Basic Usage of Cell Arraysで見た‘{’および‘}’演算子を使用して、セル配列の要素を抽出できます。セル配列のままで部分配列を抽出、またはアクセスしたい場合は‘(’および‘)’演算子を使う必要があります。この違いを以下の例で示します:
c = {"1", "2", "3"; "x", "y", "z"; "4", "5", "6"};
c{2,3}
⇒ ans = z
c(2,3)
⇒ ans =
{
[1,1] = z
}
|
So with ‘{}’ you access elements of a cell つまり‘{}’ではセル配列の要素にアクセスしますが、‘()’ではセル配列の部分配列にアクセスすることになります。
‘(’および‘)’演算子を使用することにより、多次元配列と同様にセル配列のインデクス操作を行うことができます。たとえば、以下のコマンドでセル配列のすべての行の1列目と3列目に0をセットできます。
c(:, [1, 3]) = {0}
⇒ =
{
[1,1] = 0
[2,1] = 0
[3,1] = 0
[1,2] = 2
[2,2] = 10
[3,2] = 20
[1,3] = 0
[2,3] = 0
[3,3] = 0
}
|
以下のようにも記述できることに注意してください:
c(:, [1, 3]) = 0; |
Here, the scalar ‘0’ is automatically promoted to
ここではスカラー‘0’が自動的にセル配列‘{0}’に昇格されて、cの部分配列に割り当てられています。
‘()’によるセル配列のインデクス操作として、以下のコマンドはセル配列の1行目と2行目を交換する例です:
c = {1, 2, 3; 4, 5, 6};
c([1, 2], :) = c([2, 1], :)
⇒ =
{
[1,1] = 4
[2,1] = 1
[1,2] = 5
[2,2] = 2
[1,3] = 6
[2,3] = 3
}
|
‘{’および‘}’演算子によりセル配列の複数要素にアクセスすると、結果は要求されたすべての要素のカンマ区切りリストになります(Comma Separated Listsを参照)。‘{’および‘}’演算子を使用することにより、上記の例の最初の2行は以下のように書き換えることができます:
[c{[1,2], :}] = deal (c{[2, 1], :})
⇒ =
{
[1,1] = 1
[2,1] = 4
[1,2] = 2
[2,2] = 5
[1,3] = 3
[2,3] = 6
}
|
構造体配列や数値配列のように、セル配列から要素を削除するために空マトリクス‘[]’を使用できます:
x = {"1", "2"; "3", "4"};
x(1, :) = []
⇒ x =
{
[1,1] = 3
[1,2] = 4
}
|
以下はセル配列から要素の内容だけを削除する方法を示す例です:
x = {"1", "2"; "3", "4"};
x{1, :} = []
⇒ x =
{
[1,1] = [](0x0)
[2,1] = 3
[1,2] = [](0x0)
[2,2] = 4
}
|
インデクス操作はセル配列内のオブジェクトではなく、セル配列を操作します。対照的に、cellindexmatは各セル配列エントリー内のオブジェクトにたいするマトリクスのインデクス操作に適用され、要求された値をリターンします。
与えられたマトリクスxのセル配列にたいして、この関数は以下の計算を行います
Y = cell (size (X));
for i = 1:numel (X)
Y{i} = X{i}(varargin{:});
endfor
|
See also: cellslices, cellfun.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
一般的に、セル配列は複数の文字列を1つの変数に格納するために使用されます。各行を文字列とみなせば、文字マトリクスに複数文字列を格納することもできます。しかしこれは、すべての文字列が同じ長さにしなければならないという問題が生じます。したがって、複数文字列の格納にはセル配列の使用を推奨します。ある操作に文字マトリクス表現が要求されるような場合に備えて、文字列のセル配列を文字マトリクスに変換したり、その逆を行う関数がいくつかあります。cellstrは文字配列を文字列のセル配列に変換しますが、charとstrvcatはセル配列を文字配列に変換します(Concatenating Stringsを参照)。
a = ["hello"; "world"];
c = cellstr (a)
⇒ c =
{
[1,1] = hello
[2,1] = world
}
|
文字列配列strmatの要素から、新たにセル配列オブジェクトを作成します。
strmatの各行が、cstrの要素になります。行内の末尾のスペースは、変換の前に削除されます。
文字列のセル配列から文字配列に逆変換するにはcharを使用します。
複数の文字列を格納するのにセル配列を使用する他の利点として、Octaveに同梱されている文字列を操作する関数の多くがこの表現をサポートする点が挙げられます。例として、strcmp関数を使用することにより、1つの文字列を、他の多くのものと比較できます。この関数の引数の1つが文字列で、それ以外は文字列のセル配列の場合、セル配列の各要素が文字列と比較されます:
c = {"hello", "world"};
strcmp ("hello", c)
⇒ ans =
1 0
|
次の文字列関数が文字列のセル配列をサポートします: char、strvcat、strcat
(Concatenating Stringsを参照)、strcmp、strncmp、strcmpi、strncmpi
(Comparing Stringsを参照)、str2double、deblank、strtrim、strtrunc、strfind、strmatch、regexp、regexpi
(Manipulating Stringsを参照)、str2double (String Conversionsを参照)。
関数iscellstrは、オブジェクトが文字列のセル配列かテストするのに使用できます。
セル配列cellのすべての要素が文字列の場合は、trueをリターンします。
See also: ischar.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
セル配列に格納されたデータは、実際のデータに応じて複数の方法により処理されます。forループを使用して処理を繰り返すのが、そのデータを処理するもっともシンプルな方法です。セル配列のすべての要素にユーザー定義関数を呼び出すcellfun関数の使用を通じて、さらに簡単に同じアイデアを実装できます。cellfunを参照してください。
かわりにマトリクスやデータ構造体のような、異なるコンテナーにデータを変換することもできます。データに応じてcell2mat、およびcell2struct関数の利用が可能です。
セル配列cのすべての要素を連結することによりマトリクスにして超矩形(hyperrectangle)に変換します。cの要素は数値、論理値、文字マトリクス、セル配列、構造体でなければならず、catはそれらを連結できなければなりません。
cellを構造体に変換します。fields内のフィールド数は、次元dimにしたがったcellの要素数に一致(numel
(fields) == size (cell,
dim))しなければなりません。dimが省略された場合、値は1とみなされます。
A = cell2struct ({"Peter", "Hannah", "Robert";
185, 170, 168},
{"Name","Height"}, 1);
A(1)
⇒
{
Name = Peter
Height = 185
}
|
See also: struct2cell, cell2mat, struct.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
カンマ区切りリスト(2)はすべてのOctave関数の基本的な引数型(入力引数とリターン引数の両方)です。
max (a, b) |
上記の例では‘a, b’がカンマ区切りリストです。カンマ区切りリストは代入の右辺と左辺の両方に出現することができます。たとえば
x = [1 0 1 0 0 1 1; 0 0 0 0 0 0 7]; [i, j] = find (x, 2, "last"); |
ここでは‘x, 2,
"last"’はfindの入力引数を構成するカンマ区切りリストです。findはカンマ区切りリストの出力引数をリターンし、それらは要素ごとにカンマ区切りリスト‘i,
j’に割り当てられます。
カンマ区切りリストが使用される他の例としては、[]による新たな配列の作成(Matricesを参照)や、{}によるセル配列の作成(Basic Usage of Cell Arraysを参照)があります。
a = [1, 2, 3, 4];
c = {4, 5, 6, 7};
|
この場合は‘1, 2, 3, 4’と‘4, 5, 6, 7’の両方がカンマ区切りリストです。
カンマ区切りリストはユーザーが直接扱うことはできません。しかし構造体配列とセル配列はどちらもカンマ区切りリストに変換できるので、明示的にカンマ区切りリストを記述するかわりに使用することができます。この機能は、以降のサブセクションで示すように、有用な場面が多数あります。
| 6.3.1 Comma Separated Lists Generated from Cell Arrays | ||
| 6.3.2 Comma Separated Lists Generated from Structure Arrays |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
これまで示したように(Indexing Cell Arraysを参照)、セル配列は{および}演算子でカンマ区切りリストに抽出できます。このリストを[と]で囲うことにより、配列に連結できます。たとえば:
a = {1, [2, 3], 4, 5, 6};
b = [a{1:4}]
⇒ b =
1 2 3 4 5
|
同様に{}で選択されたセル要素を含む、新たなセル配列を作成することができます。以下の例で示すように、リストを‘{’と‘}’で囲えば、新しいセル配列が作成されます:
a = {1, rand(2, 2), "three"};
b = { a{ [1, 3] } }
⇒ b =
{
[1,1] = 1
[1,2] = three
}
|
さらに({}によりアクセスされる)セル要素を、直接関数に渡すことができます。セル配列の要素リストは、あたかもその要素を引数として呼び出したかのように、関数の引数として渡すことができます。以下の例の2つのprintf呼び出しは等価ですが、後者はよりシンプルで、任意のサイズのセル配列を処理できます:
c = {"GNU", "Octave", "is", "Free", "Software"};
printf ("%s ", c{1}, c{2}, c{3}, c{4}, c{5});
-| GNU Octave is Free Software
printf ("%s ", c{:});
-| GNU Octave is Free Software
|
代入の左辺で使用する場合、{}で生成されたカンマ区切りリストに代入できます。以下は例です
in{1} = [10, 20, 30, 40, 50, 60, 70, 80, 90];
in{2} = inf;
in{3} = "last";
in{4} = "first";
out = cell (4, 1);
[out{1:3}] = find (in{1 : 3});
[out{4:6}] = find (in{[1, 2, 4]})
⇒ out =
{
[1,1] = 1
[2,1] = 9
[3,1] = 90
[4,1] = 1
[3,1] = 1
[4,1] = 10
}
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
同様に構造体配列もカンマ区切りリストの生成に使用できます。これは構造体配列の1つのフィールドをアドレッシングすることにより行われます。たとえば:
x = ceil (randn (10, 1));
in = struct ("call1", {x, 3, "last"},
"call2", {x, inf, "first"});
out = struct ("call1", cell (2, 1), "call2", cell (2, 1));
[out.call1] = find (in.call1);
[out.call2] = find (in.call2);
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
変数により、値に名前を付け、後でそれを参照できるようになります。これまで多くの例で、すでに変数を目にしてきました。変数の名前は英数字とアンダースコアのシーケンスですが、数字で開始することはできません。Octaveは変数の名前の長さに制限は強いませんが、30文字を超える長さの変数名が有用なことはまれです。以下はすべて有効な変数名です
x x15 __foo_bar_baz__ fucnrdthsucngtagdjb |
しかし、__foo_bar_baz__のように開始と終了が2つのアンダースコアの名前は、Octaveが内部で使用するために予約されています。これらの名前のは、ドキュメントされたOctaveの内部変数やビルトインシンボル定数を除き、あなたが記述するコードで使用するべきではありません。
変数名は大文字小文字を区別します。シンボルaとAは別の変数です。
変数名は、それ自体が有効な式です。変数名は、その変数の現在の値を表します。変数は代入演算子と加算演算子により新たな値が与えられます。Assignment Expressionsを参照してください。
特別な意味をもつビルトイン変数が1つあります。ans変数は、出力がどの変数にも割り当てられていないとき、常に最後の計算結果を保持します。コードa
= cos (pi)は変数aに-1を代入しますが、ansの値は変更しません。しかしコードcos
(pi)はansの値を-1にセットします。
Octaveの変数は固定された型をもたないので、変数に最初は数値を格納して、同じプログラム内で後で文字列を保持するために同じ名前を使用できます。値を与える前に変数を使用するべきではありません。これを行うと結果はエラーになります。
明示的に変数に代入されていない、もっとも最近の計算結果です。たとえば、
3^2 + 4^2 |
この式が評価された後にansがリターンする値は25です。
strから一意な変数を作成します。exclusionsが与えられた場合、それぞれの変数およびexclusionsにたいして一意になります(exclusionsには文字列とセル文字列を指定できます)。
strがセル文字列の場合は、str内の各セルにたいして一意な変数が作成されます。
x = 3.141;
genvarname ("x", who ())
⇒ x1
|
strがセル配列の場合、genvarnameは文字列を確実に分離するようにします:
genvarname ({"foo", "foo"})
⇒
{
[1,1] = foo
[1,2] = foo1
}
|
結果は変数自体ではなく、文字配列または文字列のセル配列になることに注意してください。変数の定義には、eval()を使用できます。以下はxに42をセットする例です。
name = genvarname ("x");
eval ([name " = 42"]);
⇒ x = 42
|
これは一意な構造体フィールド名の作成にも便利です。
x = struct ();
for i = 1:3
x.(genvarname ("a", fieldnames (x))) = i;
endfor
⇒ x =
{
a = 1
a1 = 2
a2 = 3
}
|
変数名に含むことができるのは英数字とアンダースコアだけなので、genvarnameは許可されていない文字シーケンスをアンダースコアで置き換えます。さらに変数名は数字で開始できないので、このような場合は変数名の最初にアンダースコアを追加します。
開始と終了が2つのアンダースコア"__"であるような変数名は有効ですが、そのような名前はoctaveにより内部的に使用されるので一般的には避けるべきで、genvarnameはそのような名前を生成しません。
またgenvarnameは"for"や"if"のようなキーワードと衝突しない名前をリターンします。必要なら数字が追加されます。しかし、これには"sin"のような函数名は含まれないことに注意してください。必要なら、そのような名前はexclusionsに含めるべきです。
MATLABと互換性のある変数名の最大長をリターンします。Octaveは長さ2^31 -
1までの文字列を格納できます。しかしMATLABとの互換性のためすべての変数、関数、構造体フィールド名はnamelengthmaxで得られる長さより短くする必要があります。特にMATLABファイルフォーマットに格納する変数は、この長さに切り詰められます。
| 7.1 Global Variables | ||
| 7.2 Persistent Variables | ||
| 7.3 Status of Variables |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
globalと宣言された変数は、それが形式にしたがって渡されたパラメーターでなくても、関数ボディーの内部からアクセスできます。
global宣言文を使用して変数をグローバルに宣言できます。以下の命令文はすべてグローバル宣言です。
global a global a b global c = 2 global d = 3 e f = 5 |
グローバル変数はglobal文で1度だけ初期化されます。たとえば、
global gvar = 1 global gvar = 2 |
この文が実行されるとグローバル変数gvarの値は2ではなく1になります。‘clear
gvar’コマンドを実行しても上記の振る舞いは変更されません。‘clear all’により変更されます。
グローバル変数にアクセスするために、関数内で変数をグローバルと宣言することが必要です。たとえば、
global x function f () x = 1; endfunction f () |
これはグローバル変数xの値を1にセットしません。グローバル変数xの値を変更するには、以下のように関数ボディー内でそれをグローバルとセットしなければなりません
function f () global x; x = 1; endfunction |
関数のパラメーターリストにグローバル変数を渡しても、それはローカルコピーを作成し、グローバルな値は変更されないでしょう。たとえば関数が以下で与えられ
function f (x) x = 0 endfunction |
トップレベルでxをグローバル変数とする定義が以下の場合
global x = 13 |
以下の式
f (x) |
は関数内部のxの値として0を表示し、トップレベルのxの値は変更されないまま残ります。なぜなら関数は引数のコピーにたいして機能するからです。
nameがグローバルに可視な変数の場合は、trueをリターンします。たとえば:
global x
isglobal ("x")
⇒ 1
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
関数内で永続的(persistent)と宣言された変数は、同じ関数にたいする一連の呼び出しの間、その内容をメモリー内にとどめます。永続的変数ちとグローバル変数に違いは、永続的変数のスコープが特定の関数にたいしてローカルであり、それ以外の場所からは不可視であることです。
以下は、永続的変数を使用して、呼び出された回数をプリントする関数を作成する例です。
function count_calls ()
persistent calls = 0;
printf ("'count_calls' has been called %d times\n",
++calls);
endfunction
for i = 1:3
count_calls ();
endfor
-| 'count_calls' has been called 1 times
-| 'count_calls' has been called 2 times
-| 'count_calls' has been called 3 times
|
例示すように変数persistent宣言文により永続的であると宣言されます。以下の命令文はすべて永続的な宣言です。
persistent a persistent a b persistent c = 2 persistent d = 3 e f = 5 |
永続的変数の振る舞いは、Cの静的変数と同じです。Octaveではコマンドstaticも認識され、これはpersistentと等価です。
グローバル変数と同様、永続的変数は1度だけ初期化されます。たとえば、
persistent pvar = 1 persistent pvar = 2 |
この式を実行すると、永続的変数pvarの値じゃ2ではなく1になります。
永続的変数が宣言されていても特定の値に初期化されていない場合、値は空マトリクスになります。したがって以下の例で示すように、空かどうかチェックすることにより永続的変数を初期化することも可能です。
function count_calls ()
persistent calls;
if (isempty (calls))
calls = 0;
endif
printf ("'count_calls' has been called %d times\n",
++calls);
endfunction
|
この実装は、count_callsの以前の実装と正確に同じ方法で振る舞います。
永続的変数の値は、明示的にクリアーされるまでメモリー内にとどまります。count_callsの実装がディスク上に保存されていると仮定すると、以下のような振る舞いになります。
for i = 1:2 count_calls (); endfor -| 'count_calls' has been called 1 times -| 'count_calls' has been called 2 times clear for i = 1:2 count_calls (); endfor -| 'count_calls' has been called 3 times -| 'count_calls' has been called 4 times clear all for i = 1:2 count_calls (); endfor -| 'count_calls' has been called 1 times -| 'count_calls' has been called 2 times clear count_calls for i = 1:2 count_calls (); endfor -| 'count_calls' has been called 1 times -| 'count_calls' has been called 2 times |
つまり、変数を含む関数がメモリーから削除されるときだけ、永続的変数が削除されます。Octaveから関数定義を直接タイプした場合は、メモリーから関数定義全体を削除するclearコマンドにより、永続的変数が削除されます。関数がクリアーされてもメモリーから永続的変数を削除したくない場合は、mlock関数を使用するべきです(Function Lockingを参照)。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
シンプルな使い捨てプログラムを作成する場合、プロンプト上でどの変数が利用できるととても便利なことがあります。関数who、および同類のwhosとwhos_line_formatは以下で示すように、メモリー内に何があるかについて異なる情報を表示します。
str = "A random string";
who -variables
-| *** local user variables:
-|
-| __nargin__ str
|
与えられたパターンにマッチする現在定義されている変数をリストします。有効なパターン構文は、clearコマンドで説明されているものと同じです。パターンが与えられない場合は、すべての変数がリストされます。デフォルトでは、ローカルスコープで可視な変数だけが表示されます。
以下は有効なオプションですが、組み合わせることはできません。
globalカレントスコープではなく、グローバルスコープの変数をリストします。
-regexpパターンは表示する変数をマッチングするときの正規表現です。regexp関数を使用するときと同じパターン構文を指定できます。
-file次の引数をファイル名として扱います。指定されたファイルで見つかったすべての変数がリストされます。ファイルから変数を読み込むとき、パターンは指定できません。
関数として呼び出された場合は、与えられたパターンにマッチする定義された変数名のセル配列をリターンします。
与えられたパターンにマッチする、現在定義された変数の詳細な情報を提供します。オプションとパターン構文は、whoコマンドと同じです。各変数についての拡張された情報は、以下のデフォルトエントリーとともにテーブルに要約されます。
リストされた変数の属性。
ローカルスコープの変数
a自動変数。自動変数とは、インタープリターにより作成されたもの。例: argn
c複素数型の変数
f通常形式のパラメーター(関数の引数)。
gグローバルスコープの変数。
p永続的変数。
変数の名前。
変数の論理的サイズ。スカラーは1x1、ベクターは1xNまたはNx1、2次元マトリクスはMxN。
変数を格納するために現在使用されているメモリーの量。
変数のクラス。たとえばdouble、single、char、uint16、cell、struct。
関数whos_line_formatを通じて表示される情報の加減をカスタマイズできます。
関数としてwhosが呼び出された場合は、与えられたパターンにマッチする定義された変数名の構造体配列をリターンします。構造体の各フィールドはname、size、bytes、class、global、sparse、complex、nesting、persistentを表します。
See also: who, whos_line_format.
コマンドwhosで使用されるフォーマット文字列にたいして、問い合わせまたはセットを行います。
以下は完全なフォーマット文字列です:
%[modifier]<command>[:width[:left-min[:balance]]]; |
以下のコマンドシーケンスが利用できます:
%a変数の属性をプリントする(g=global、p=persistent、f=formal parameter、a=automatic variable)。
%b変数が占めるバイト数をプリントする。
%c変数のクラス名をプリントする。
%e変数が保持する要素をプリントする。
%n変数名をプリントする。
%s変数の次元をプリントする。
%t変数の型名をプリントする。
各コマンドはアラインメント修飾子ももつ:
l左揃え。
r右揃え(デフォルト)。
c列揃え(コマンド%sでのみ指定可)。
widthはプリントに使用される最小列値を指定する正の整数です。フィールドは必要に応じて自動的に拡張されるので、最大値は必要ありません。
パラメーターleft-minおよびbalanceは、コマンド‘%s’とともに列アラインメント修飾子が使用されたときだけ利用可能です。balanceはエントリー間を整列するフィールド幅を列数で指定します。ナンバリングは最左列を意味する0から開始されます。left-minは指定されたバランス列の左側の最小フィールド幅を指定します。
デフォルトフォーマットは" %a:4; %ln:6; %cs:16:6:1; %rb:12; %lc:-1;n"です。
関数内から"local"オプションとともに呼び出された場合、変数の変更はその関数および関数のサブルーチンにたいしてローカルになります。関数をexitするとき、変数の元の値がリストアされます。
See also: whos.
どの変数がメモリー内にあるか表示するかわりに、与えられた変数が利用可能か判定することができます。この方法は、変数の存在によりプログラムの挙動を変えることにより可能になります。以下はこれを示す例です。
if (! exist ("meaning", "var"))
disp ("The program has no 'meaning'");
endif
|
nameが変数として存在する場合は1、絶対ファイル名、またはOctaveのpath上の通常ファイルか(‘.m’を追加することにより)関数ファイルの場合は2、Octaveのpath上の‘.oct’または‘.mex’ファイルの場合は3、ビルトイン関数の場合は5、ディレクトリの場合は7、ファイルに関連付けされていない(コマンドラインで入力された)関数の場合は103をリターンします。
それ以外は0をリターンします。
この関数はOctaveの検索パスにあるnameという名前の通常ファイルの場合は、2をリターンします。他のファイル型についての情報が欲しい場合は、かわりに関数file_in_pathおよびstatを組み合わせて使用するべきです。
オプション引数typeが与えられた場合は、シンボルで指定された型だけをチェックします。有効な型は
"var"変数だけをチェック。
"builtin"ビルトイン関数だけをチェック。
"file"ファイルとディレクトリだけをチェック。
"dir"ディレクトリだけをチェック。
See also: file_in_loadpath, file_in_path, find_dir_in_path, stat.
通常Octaveはメモリーを管理しますが、メモリーから手動で変数を削除するのが実用的な場合もあるでしょう。これは通常、メモリーの相当量を占める大きな変数を扱うとき必要になります。IEEE浮動小数点フォーマットを使用するコンピューターでは、以下のプログラムは約128MBのメモリーを要求するマトリクスを割り当てます。
large_matrix = zeros (4000, 4000); |
この変数をメモリー上に保持することは、他の計算の速度低下を招くかもしれないので、メモリーから手動で削除する必要があります。clear関数により、これを行うことができます。
シンボルテーブルから、与えられたパターンにマッチする名前を削除します。パターンは、以下の特殊文字を含むことができます:
?任意の1文字にマッチ。
*0文字以上にマッチ。
[ list ]listで指定された文字リストにマッチ。1文字目が!か^の場合はlistで指定された文字以外のすべての文字にマッチ。たとえば、‘[a-zA-Z]’はすべてのアルファベットの小文字と大文字にマッチ。
たとえば、
clear foo b*r |
は名前fooと、bで始まりrで終わるすべての名前をクリアーします。
引数を指定せずにclearが呼び出された場合、シンボルテーブルからすべてのユーザー定義変数(ローカルおよびグローバル)がクリアーされます。少なくとも1つの引数とともにclearが呼び出された場合は、引数にマッチする可視の名前だけがクリアーされます。たとえば、関数fooを定義して、その後に代入foo
= 2を行ってそれを隠したとします。コマンドclear
fooを1度実行することにより、変数定義がクリアーされ、関数としてのfooの定義がリストアされます。clear
fooの2度目の実行により、関数定義がクリアーされます。
短い形式と長い形式の両方で、以下のオプションが利用できます
-all, -aシンボルテーブルから、ローカルおよびグローバルのユーザー定義変数とすべての関数をクリアーする。
-exclusive, -x後のパターンにマッチしない変数をクリアーする。
-functions, -f関数とビルトインシンボル名をクリアーする。
-global, -gグローバルシンボル名をクリアーする。
-variables, -vローカル変数名をクリアーする。
-classes, -cクラス構造体テーブルちすべてのオブジェクトをクリアーする。
-regexp, -r引数は正規表現と解釈され、それにマッチする変数をクリアーする。
exclusiveの例外として、ダッシュなしのロングオプションも同様に使用できる。
MATLABではワークスペースのメモリーを統合します。この関数は互換性のために提供されており、Octaveでは何も行いません。
関数や変数について、それがファイルシステム上どの位置にあるかなどの情報も、Octaveにより収集できます。これは通常プログラム開発の間のみ有用で、プログラムにとって有用ではありません。
nameの内容を表示します。nameにはファイル、関数(m-file)、変数、演算子、キーワードを指定できます。
typeは通常、functionやvariableのようにnameのカテゴリーを記述するヘッダー行を前置します。‘-q’オプションにより、この動作を抑制できます。
出力変数が指定されていない場合、内容はスクリーンに表示されます。それ以外は文字列のセル配列がリターンされます。この場合、各要素が要求されあ関数の内容に対応します。
nameのそれぞれの型を表示します。nameが関数ファイルで定義される場合は、ファイルの関数名も表示されます。
ディレクトリdir内のOctave固有のファイルをリストします。dirが指定されない場合は、カレントディレクトリが使用されます。リターン引数が要求された場合、構造体w内に見つかったファイルがリターンされます。
See also: which.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
式はOctaveにおける命令文の基本的な構築ブロックです。式は値に評価され、その値をプリント、テスト、変数に格納、関数に渡すことができ、代入演算子で変数に新たな値を割り当てることもできます。
式は自身の命令文の役割りも果たすことができます他の種の命令文の多くは、処理を行うデータを指定する、1つ以上の式を含みます。他言語と比較して、Octaveの式は変数、配列参照、定数、関数呼び出しを含み、同様にさまざまな種類の演算子によるそれらの組み合わせも含みます。
| 8.1 Index Expressions | ||
| 8.2 Calling Functions | ||
| 8.3 Arithmetic Operators | ||
| 8.4 Comparison Operators | ||
| 8.5 Boolean Expressions | ||
| 8.6 Assignment Expressions | ||
| 8.7 Increment Operators | ||
| 8.8 Operator Precedence |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
インデクス式(index expression)により、マトリクスysベクターの選択した要素の参照と抽出が可能になります。
インデクスはスカラー、ベクター、レンジ、または行や列全体の選択に使用する特殊演算子‘:’です。
ベクターは1つにインデクス式を使用してインデクス付けされます。マトリクス(2次元)およびより高次の多次元配列は、1つのインデクスまたはN個(Nは配列の次元)のインデクスによりインデクス付けされます。2次元またはより高次のデータを1つのインデクス式でインデクス付けする場合、配列の要素は(Fortranのように)列優先で取得されます。
インデクス操作による出力はインデクス式の次元とみなされます。たとえば:
a(2) # 結果はスカラー a(1:2) # 結果はベクター a([1; 2]) # 結果は列ベクター |
特殊なケースとして、コロンが1つのインデクスとして使用された場合、出力はベクターまたはマトリクスのすべての要素を含む列ベクターになります。たとえば:
a(:) # 結果は列ベクター a(:)' # 結果は行ベクター |
上記2つのコード用法は、reshapeなどで任意サイズの配列ではなくシンプルなベクターが必要なとき用いられます。
以下のマトリクスが与えられたとき
a = [1, 2; 3, 4] |
以下の式はすべて等価で、いずれもマトリクスの最初の行を選択します。
a(1, [1, 2]) # 行 1, 列 1、2 a(1, 1:2) # 行 1, 列のレンジ 1-2 a(1, :) # 行 1, 列全体 |
インデクス式において、キーワードendは特定の次元の最後のエントリーを自動的に参照します。このマジックインデクスはレンジで使用することもでき、インデクス操作前に配列範囲を得るためのsizeとlengthの呼び出しの必要性をなくします。たとえば:
a = [1, 2, 3, 4]; a(1:end/2) # aの最初の半分 => [1, 2] a(end + 1) = 5; # 要素の追加 a(end) = []; # 要素の削除 a(1:2:end) # aの奇数要素 => [1, 3] a(2:2:end) # aの偶数要素 => [2, 4] a(end:-1:1) # aの逆 => [4, 3, 2 , 1] |
| 8.1.1 Advanced Indexing |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
‘n’次元の配列を‘m’次元のインデクスでインデクス付けできます。より一般的には結果を決定するインデクスセットはインデクスベクター(またはレンジ、スカラー)は直積(Cartesian product: カルテシアン積、デカルト積)により形成されます。
通常、そしてもっとも一般的なケースはm == nで、各インデクスはそれぞれの次元に対応します。m <
nで各インデクスがi番目の次元において配列サイズより小さい場合、インデクス式は末尾のシングルトン次元([ones
(m-n, 1)])とともに渡されます。m <
nだがインデクスの1つm(i)が現在の配列のサイズの外側の場合、最後のn-m+1次元が元の次元を掛け合わせた結果と等しくなるように拡張されてシングルトン次元に折り畳まれます。例で理解するのがもっとも簡単でしょう。
a = reshape (1:8, 2, 2, 2) # 3次元配列を作成
a =
ans(:,:,1) =
1 3
2 4
ans(:,:,2) =
5 7
6 8
a(2,1,2); # (m == n)の場合: ans = 6
a(2,1); # (m < n)の場合、インデクスは配列内
# a(2,1,1)に等しい: ans = 2
a(2,4); # (m < n)の場合、インデクスは配列の外側
# 次元2と3は、サイズ2x2 = 4の新たな次元に折り畳まれる
# 2行目[2, 4, 6, 8]の4番目の要素が選択される: ans = 8
|
インデクスの上級の使用法としては、1つの値で満たされた配列の作成があります。これはonesのインデクスをスカラー値に使用して行うことができます。結果はインデクス式の次元をもち、各要素が元のスカラーに等しいオブジェクトになります。たとえば以下の命令文
a = 13; a(ones (1, 4)) |
これは4つの要素すべてが13のベクターを生成します。
同様に2つのonesベクターによりスカラーをインデクス付けすることにより、マトリクスを作成できます。以下の命令文
a = 13; a(ones (1, 2), ones (1, 3)) |
これはすべての要素が13と等しい2x3のマトリクスを作成します。
最後の例は以下のように記述することもできます
13(ones (2, 3)) |
不要な乗算を避けることができるので、scalar * ones (N, M,
…)とコードを構築するよりインデクス操作を使用するほうがより効果的です。さらに複製されるオブジェクトには乗算が定義されていないかもしれませんが、配列へのインデクス操作は常に定義されています。以下は、それ自身がスカラーではない基本ユニットから、2x3のセル配列を作成する方法を示します。
{"Hello"}(ones (2, 3))
|
ones (1,
n)(onesの行ベクター)の結果は、(増分が0の)レンジとなることは注記しておくべきでしょう。内部的にレンジは開始値、増分、終値、値の合計として格納されます。したがって、要素数が4より大のときは常にonesのベクターまたはマトリクスのほうが、記憶領域にたいして効果的です。特に‘r’が行ベクターの場合、以下の式
r(ones (1, n), :) |
r(ones (n, 1), :) |
これは同じ結果を生成しますが、少なくとも‘r’と‘n’が十分大きければ、1つ目のほうが明らかに高速です。最初のケースでは、インデクスはOctaveが式を処理するためにより効果的なアルゴリズムを選択できるレンジ形式として、圧縮されて保持されます。
これらの違いを理解しないユーザーには、一般的に小さな配列を大きな配列に複製する場合は、関数repmatの使用を推奨します。
2つ目のインデクス操作の用途は、コードのスピードアップです。インデクス操作は高速な処理であり、慎重に使用することにより、特定の配列要素をループするような低速な処理の必要を低減できます。
以下のような値をもつ10要素の行ベクターaを作成する例で考えてみましょう a(i) = sqrt (i).
for i = 1:10 a(i) = sqrt (i); endfor |
このようなループを使用してベクターを作成するのは、効果的ではありません。この場合は、以下のような式を使用するほうがより効果的でしょう
a = sqrt (1:10); |
これはループ全体の使用を避けています。
ループを避けることができず、値の数が巨大なマトリクスの形成に結びついている場合、最初にマトリクスのサイズをセット(事前領域割り当て)してから、インデクスコマンドを使用して要素を挿入するほうが、一般的にはより高速です。たとえば、マトリクスaが与えられた場合、
[nr, nc] = size (a); x = zeros (nr, n * nc); for i = 1:n x(:,(i-1)*nc+1:i*nc) = a; endfor |
この式は、以下に比べてはるかに高速です
x = a; for i = 1:n-1 x = [x, a]; endfor |
なぜなら、Octaveが中間結果を繰り返しリサイズする必要がないからです。
添字を線形のインデクスに変換します。
以下は3行3列のマトリクスの2次元インデクス(2,3)を線形インデクスに変換する方法を示す例です。マトリクスは列から列へ、各列のすべての行が満たされるまで、線形にインデクス付けされます。
linear_index = sub2ind ([3, 3], 2, 3) ⇒ 8 |
See also: ind2sub.
線形のインデクスを添字に変換します。
以下は3行3列のマトリクスの線形インデクス8を添字に変換する方法を示す例です。マトリクスは列から列へ、各列のすべての行が満たされるまで、線形にインデクス付けされます。
[r, c] = ind2sub ([3, 3], 8)
⇒ r = 2
⇒ c = 3
|
See also: sub2ind.
indが有効なインデクスの場合は、trueをリターンします。有効なインデクスとは、正の整数(実際は実数データ型ですが)、または論理配列です。nが与えられた場合、それはインデクス付けされる次元の拡張の最大を指定します。可能なら結果は内部でキャッシュされるので、indを連続して使用する場合、再チェックを行いません。
非整数レンジをインデクスに使用できるかどうかを制御する内部変数にたいして、問い合わせまたはセットを行います。これはMATLABとの互換性にたいしては有用です。しかし、MATLABはレンジ式にたいして、異なるコンテキストで異なる扱いをするため、完全な互換性はありません。
関数内から"local"オプションとともに呼び出された場合、変数の変更はその関数および関数のサブルーチンにたいしてローカルになります。関数をexitするとき、変数の元の値がリストアされます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
関数(function)とは、特定の計算にたいする名前です。名前をもつので、プログラム内の任意の場所で名前で問い合わせることができます。たとえば、関数sqrtは数値の平方根を計算します。
関数のある固定されたセットはビルトインで、すべてのOctaveプログラム内でそれらを利用できることを意味します。sqrt関数は、そのうちの1つです。さらに、あなたが自分の関数を定義できます。これを行うための情報は、Functions and Scriptsを参照してください。
関数呼び出し式で関数を使用します。これは関数の後にカッコで括った引数リストを続けて構成されます。引数は、その関数が行うであろう計算のための、生の材料を与えます。2つ以上の引数がある場合は、カンマで区切ります。引数がない場合はカッコを省略できますが、関数呼び出しが意図されていることを明確に示すために、カッコを含めるのは良いアイデアです。以下にいくつか例を示します:
sqrt (x^2 + y^2) # 引数=1 ones (n, m) # 引数=2 rand () # 引数なし |
関数はそれぞれ、特定の個数の引数を期待します。たとえばsqrt関数は平方根を求める数値を1つの引数として呼び出さなければなりません:
sqrt (argument) |
ビルトイン関数には、可変個の引数をとるものがいくつかあります。引数の数は使い方に依存して異なり、与えられた引数の数に応じて異なった振る舞いをします。
他のすべての式と同様、関数呼び出しは値であり、値は与えられた引数に基づきその関数により計算されます。この例では、sqrt
(argument)の値は、引数の平方根です。関数は、特定の変数に値を割り当てたり、入出力処理を行うような、副作用もあります。
他の多くの言語と異なり、Octaveの関数は複数の値をリターンします。たとえば、以下の命令文
[u, s, v] = svd (a) |
これはマトリクスaのsingular value
decompositionを3つの結果マトリクスu、s、vに割り当てます。
複数代入式の左辺は、それ自体がリスト式であり、変数名リストまたはインデクス式を記述できます。Index ExpressionsとAssignment Expressionsも参照してください。
| 8.2.1 Call by Value | ||
| 8.2.2 Recursion |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
OctaveではFortranと異なり関数の引数は値で渡されます。これは関数に渡される前に関数呼び出しの各引数が評価されて、一時的な場所に割り当てられることを意味します。関数のパラメーターを値ではなく参照であると指定する方法は、現在のところありません。これは呼び出された関数内で直接関数パラメーターの値を変更することは不可能であることを意味します。関数ボディー内のローカルコピーだけが変更できます。たとえば、
function f (x, n)
while (n-- > 0)
disp (x);
endwhile
endfunction
|
この関数は1つ目の引数をn回表示します。この関数では、呼び出された関数内で値が変更されることを心配しなくてもよい、一時的な変数として変数nを使用しています。値呼出しは最初にその関数がパラメーターの変更を試みないか判断する必要なく、常に定数を任意の関数パラメーターとすることができます。
呼び出し側は引数に変数として式を使用できますが、呼び出された関数はこれを知りません。知っているのは引数がもつ値だけです。たとえば、以下の関数呼び出しが与えられた場合
foo = "bar"; fcn (foo) |
これを“変数foo”が引数だと考えるべきではありません。かわりに、引数を文字列値"bar"と考えるべきです。
たとえOctaveが関数の引数に値渡しのセマンティックを使用していても、不必要に値はコピーされません。たとえば、
x = rand (1000); f (x); |
この式は、関数fが引数を変更するまでは、実際に1000x1000のマトリクス要素2つが存在することを強いません。その後でOctaveは関数fのスコープ外で値が変更されたり、定数または一時的な結果値にたいする修正の試み(おそらく失敗します!)を避けるためにコピーを作成しなければならなくなります。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
いくつかの制限(3)により、再帰関数呼び出しは許されません。再帰関数とは、直接または間接的に自身を呼び出す関数です。たとえば、以下は与えられた整数の階乗を計算する、非効率的(4)な方法の例です:
function retval = fact (n)
if (n > 0)
retval = n * fact (n-1);
else
retval = 1;
endif
endfunction
|
この関数は自身を直接呼び出すので、再帰的です。これは呼び出すごとに、以前の呼び出しより1少ない引数を使用するので、最終的には終了します。一度引数が0以下になれば、自身を呼び出さず、再帰は終了します。
ビルトイン変数max_recursion_depthは、再帰の深さを制限し、Octaveが永久に再帰するのを防ぎます。
関数が再帰的に呼び出される回数の内部制限にたいして、問い合わせまたはセットを行います。制限を超過した場合はエラーメッセージがプリントされ、制御はトップレベルに戻されます。
関数内から"local"オプションとともに呼び出された場合、変数の変更はその関数および関数のサブルーチンにたいしてローカルになります。関数をexitするとき、変数の元の値がリストアされます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
以下の算術演算子が利用でき、それらはスカラーとマトリクスにたいして機能します。要素対要素の演算子と関数はブロードキャストします(Broadcastingを参照)。
加算。オペランドがどちらもマトリクスの場合、行数と列数が一致するか、同じ形体にブロードキャスト可能でなければならない。
要素ごとの加算。この演算子は+と等価。
減算。オペランドがどちらもマトリクスの場合は、行数と列数が一致するか、同じ形体にブロードキャスト可能でなければならない。
要素ごとの減算。この演算子は-と等価。
マトリクスの乗算。xの列数は、yの行数に一致するか、同じ形体にブロードキャスト可能でなければならない。
要素ごとのの乗算。オペランドがどちらもマトリクスの場合は、行数と列数が一致するか、同じ形体にブロードキャスト可能でなければならない。
右除算。これは以下の式と概念的に等価
(inverse (y') * x')' |
しかしy’を逆転せずに計算される。
システムがsquareeではない、または係数行列が非正則の場合は、minimum norm solutionが計算されます。
要素ごとの右除算。
左除算。これは以下の式と概念的に等価
inverse (x) * y |
しかしxを逆転せずに計算される。
システムがsquareeではない、または係数行列が非正則の場合は、minimum norm solutionが計算されます。
要素ごとの左除算。yの各要素は、対応するxの要素により除される。
べき乗演算子。xとyがどちらもスカラーの場合、この演算子はxをy乗じてリターンする。xがスカラーでyが正方マトリクスの場合、結果は固有値展開を使用して計算される。xが正方マトリクスの場合、yが整数なら結果は乗算を繰り返して計算され、yが非整数なら固有値展開により計算される。xとyが両方マトリクスなら結果はエラーとなる。
この演算子の実装は改善される必要がある。
要素ごとのべき乗演算子。オペランドがどちらもマトリクスの場合、行数と列数が一致するか、同じ形体にブロードキャストされなければならない。複素数の結果が複数利用できる場合、最小の非負(angle)の引数が採用される。このルールにより、たとえ実数の根が利用できても、複素数の根がリターンされる。実数の結果を望むならrealpow、realsqrt、cbrt、nthrootを使用すること。
Negation.
単項プラス。この演算子はオペランドに影響を与えない。
複素数の共役転置。実数の引数にたいして、この演算子は転置演算子と等価。複素数引数にたいして、この演算子は以下の式と等価
conj (x.') |
転置。
Octaveの要素ごとの演算子は‘.’で始まり、以下のような文にたいして曖昧さが存在することに注意してください
1./m |
なぜならピリオドは定数の一部、あるいは演算子の一部としてどちらにも解釈できるからです。この競合を解決するために、Octaveはあたかも以下をタイプしたかのように扱い
(1) ./ m |
以下のように扱うことはありません
(1.) / m |
これは、与えられた任意の位置において最長のマッチが優先されるというOctave字句解析の通常の振る舞いと統一が取れませんが、この場合はこちらのほうが便利です。
複素数のxの共役転置をリターンします。この関数とx'は等価です。
See also: transpose.
xとyの要素ごとの左除算をリターンします。この関数とx .\
yは等価です。
xとyの左除算マトリクスをリターンします。この関数はx \
yと等価です。
xのy乗というべき乗操作を行いマトリクスをリターンします。この関数はx ^ yと等価です。
xとyを右除算したマトリクスをリターンします。この関数はx / yと等価です。
入力のmultiplication productをリターンします。この関数とx *
yは等価です。より多くの引数が与えられた場合、multiplicationは累積的に左から右へと行われます:
(…((x1 * x2) * x3) * …) |
少なくとも1つの引数が要求されます。
See also: times, plus, minus, rdivide, mrdivide, mldivide, mpower.
この関数はx + yと等価です。より多くの引数が与えられた場合、加算は左から右へ累積的に行われます:
(…((x1 + x2) + x3) + …) |
少なくとも1つの引数が要求されます。
要素ごとにxをy乗してリターンします。複数の複素数結果が利用できる場合は、最小の非負(angle)の引数をリターンします。実数の結果が望ましい場合はrealpow、realsqrt、cbrt、nthrootを使用してください。
この関数はx .^ yと等価です。
xとyを要素ごとに右除算してリターンします。この関数はx ./ yと等価です。
入力の要素ごとのmultiplication productをリターンします。この関数とx .*
yは等価です。より多くの引数が与えられた場合、乗算は左から右に累積的に適用されます:
(…((x1 .* x2) .* x3) .* …) |
少なくとも1つの引数が要求されます。
xの転置をリターンします。この関数とx.'は等価です。
See also: ctranspose.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
比較演算子は等価性のような関連について数値を比較します。これらは関係演算子を用いて記述されます。
Octaveのすべての比較演算子は、比較がtrueなら1、falseなら0をリターンします。マトリクス値にたいしては、すべて要素ごとの原理に基づき機能します。ブロードキャストのルールが適用されます。Broadcastingを参照してください。たとえば:
[1, 2; 3, 4] == [1, 3; 2, 4]
⇒ 1 0
0 1
|
ブロードキャストのルールにしたがい、オペランドの1つがスカラーで、もう一方がマトリクスの場合は、そのスカラーがマトリクスの各要素と順に比較され、結果はそのマトリクスと同じサイズになります。
x < yxがyより小ならtrue。
x <= yxがy以下ならtrue。
x == yxがyと等しければtrue。
x >= yxがy以上ならtrue。
x > yxがyより大ならtrue。
x != yx ~= yxがyとしくなければtrue。
複素数値にたいしては以下の順序が定義されている(z1 < z2の場合に限る)。
abs (z1) < abs (z2) || (abs (z1) == abs (z2) && arg (z1) < arg (z2)) |
これはmax、min、sortで使用される順序と整合がとれていますが、実数部だけを比較するMATLABとは不整合です。
文字列の比較は上記にリストした演算子ではなく、strcmp関数により処理されます。Stringsを参照してください。
2つの入力が等しければtrueをリターンします。この関数はx == yと等価です。
x1、x2、…がすべて等しければtrueをリターンします。
See also: isequaln.
NaN == NaNという追加の仮定のもとに、x1、x2、…のすべてが等しければtrueをリターンします(データセット内のNaNの代替物の比較は行いません)。
See also: isequal.
2つの入力が等しくなければtrueをリターンします。この順序はx != yと等価です。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 8.5.1 Element-by-element Boolean Operators | ||
| 8.5.2 Short-circuit Boolean Operators |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
要素ごとの論理式は、ネストを制御するカッコとともにブール演算子“or” (‘|’)、“and” (‘&’)、“not” (‘!’)を使用します。ブール式のtrueはコンポーネント式の対応する要素の論理値を組み合わせて計算されます。値が0の場合はfalse、それ以外はtrueと判断されます。
要素ごとのブール式は、比較式が使える場所ならどこでも使用できます。これらifやwhileなどの命令文内で使用されます。しかしifやwhileなどの命令文内の条件としてマトリクス値が使用される場合は、マトリクスのすべての要素が非0のときだけtrueになります。
比較演算子と同様、要素ごとのブール式は数値(1はtrue、0はfalse)をもち、ブール式の結果をを変数に格納したり、数学的に使用された場合に効果を発揮します。
以下は3つの要素ごとのブール演算子の説明です。
boolean1 & boolean2対応する要素boolean1とboolean2の両方がtrueのとき、結果要素はtrue。
boolean1 | boolean2対応する要素boolean1とboolean2のどちらか一方がtrueのとき、結果要素はtrue。
! boolean~ boolean対応する要素booleanがfalseのとき、結果要素はtrue。
これらの演算子は、要素ごとの原理にもとづき機能します。たとえば、以下の式
[1, 0; 0, 1] & [1, 0; 2, 3] |
は2行2列の単位マトリクスをリターンします。
2項演算子にたいしては、ブロードキャストルールが適用されます。Broadcastingを参照してください。特にオペランドの1つがスカラーで、もう一方がマトリクスの場合、しの演算子はスカラーとマトリクスの各要素に適用されます。
要素ごとの2項ブール演算子にたいしては、結果を計算する前に部分式boolean1とboolean2が評価されます。。これは、式が副作用をもつとき、違いを生じます。たとえば、以下の式
a & b++ |
これは、たとえaが0でも、変数bの値はインクリメントされます。
この振る舞いは説明したように、マトリクス値をもつオペランドにたいしてブール演算子が機能するために必要なのです。
xとyの論理的ANDをリターンします。この関数はx &
yと等価です。より多くの引数が与えられた場合、論理的ANDは左から右へと累積的に適用されます:
(…((x1 & x2) & x3) & …) |
少なくとも1つの引数が要求されます。
xとyの論理的ORをリターンします。この関数はx |
yと等価です。より多くの引数が与えられた場合、論理的ORは左から右へと累積的に適用されます:
(…((x1 | x2) | x3) | …) |
少なくとも1つの引数が要求されます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
ifやwhileの中での暗黙的なスカラー値への変換と組み合わせれば、Octaveの要素ごとのブール演算子は、論理演算の大部分を処理するのに十分です。しかし、全体の論理値が判断されたらすぐにブール式の評価を停止するのが望ましい場合もあります。Octaveのブール演算子のショートサーキットは、この方法で機能します。
boolean1 && boolean2式boolean1は、all
(boolean1(:))と等価な処理を使用して、スカラーに評価・変換されます。これがfalseの場合、式全体の結果は0になります。trueの場合、式boolean2はall
(boolean1(:))と等価な処理を使用して、スカラーへと評価・変換されます。trueの場合、式全体の結果は1になります。それ以外は、式全体の結果は0になります。
警告: all
(boolean1(:))の評価ルールには、boolean1が空マトリクスの場合に、1つの例外があります。空マトリクスの論理値は空マトリクスにたいして常にfalseなので、たとえall
([])がtrueでも、[] && trueはfalseに評価されます。
boolean1 || boolean2式boolean1は、all
(boolean1(:))と等価な処理を使用して、スカラーに評価・変換されます。trueの場合、式全体の結果は1になります。falseの場合、all
(boolean1(:))と等価な処理を使用して、式boolean2がスカラーに評価・変換されます。trueの場合、式全体の結果は1になります。それ以外は、式全体の結果は0になります。
警告: 空マトリクスの論理値は常にfalseになります。詳細は上記リストのアイテムを参照してください。
式全体の論理値が決定される前に両方のオペランドが評価されることはないという事実は重要です。たとえば、以下の式
a && b++ |
変数aが非0の場合のみ、変数bの値はインクリメントされます。
これは、より簡潔なコードを記述するのに使用できます。たとえば、
function f (a, b, c)
if (nargin > 2 && ischar (c))
…
|
存在しない引数の評価を避けるために2つのif文を使用するかわりに、上記のように記述することが可能です。たとえば、ショートサーキット機能がなければ、以下のように記述する必要があるでしょう
function f (a, b, c)
if (nargin > 2)
if (ischar (c))
…
|
以下のように記述すると
function f (a, b, c)
if (nargin > 2 & ischar (c))
…
|
fが1つ、または2つの引数で呼び出された場合にエラーとなります。なぜならOctaveは演算子‘&’にたいして、両方のオペランドの評価を強いるからです。
MATLABは、ifおよびwhile文の論理式内で使用されたとき、演算子‘&’と‘|’がショートサーキットのために特別に振る舞うことを許しています。Octaveパーサーもおそらく同じ振る舞いを指示するでしょうが、この使用法は推奨されません。
ifまたはwhile文の条件部の内部で、‘|’および‘&’演算子が評価のショートサーキットを行うかどうかを制御する内部変数にたいして、問い合わせまたはセットを行います。
この機能はMATLABとの互換性のためだけに提供されており、この機能にもとづいた古いコードを移植するのでなければ、使用するべきではありません。
新しいプログラムで論理式のショートサーキット動作を得るには、常に‘&&’および‘||’演算子を使用するべきです。
関数内から"local"オプションとともに呼び出された場合、変数の変更はその関数および関数のサブルーチンにたいしてローカルになります。関数をexitするとき、変数の元の値がリストアされます。
最期に、Octaveでは三項演算子(?:)はサポートされません。ショートサーキットが重要でなければ、ifelse関数で置き換えることができます。
maskの値に応じて、true_valとfalse_valの要素をマージします。maskが論理的スカラーの場合、他の2つの引数は任意の値をとることができます。それ以外は、maskは論理的配列でなければならず、tvalとfvalはマッチングするクラスかセル配列です。スカラーマスクの場合、maskがtrueならtvalがリターンされ、それ以外はfvalがリターンされます。
配列マスクの場合、tvalとfvalはどちらもスカラーか、maskと次元が等しい配列でなければなりません。以下のように結果が構築されます:
result(mask) = tval(mask); result(! mask) = fval(! mask); |
maskは任意の数値型でもよく、この場合は最初に論理値に変換されます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
割り当てとは、変換に新しい値を格納することです。たとえば、以下の式は変数zに値1を代入します:
z = 1 |
この式が実行されると、変数zは値1をもちます。zの古い値が何であれ、以前に割り当てられていた値は忘れられます。‘=’記号は、代入演算子と呼ばれます。
代入により文字列値も格納できます。たとえば、以下の式は変数messageに値"this food is
good"を格納します:
thing = "food" predicate = "good" message = [ "this " , thing , " is " , predicate ] |
(これは文字列の連結も示しています。)
大部分の演算子(追加、連結など)は、値の計算以外の効果はもちません。値が不要なら、演算子を使用することもないでしょう。代入演算子は異なります。これは値を生成しますが、たとえ値を無視しても、変数の変更により代入は効果をもちます。これを副作用と呼びます。
代入の左辺のオペランドは、変数である必要はありません(Variablesを参照)。マトリクスの要素(Index Expressionsを参照)や、リターン値のリスト(Calling Functionsを参照)でも可能です。これらはすべて左辺値(lvalues)と呼ばれ、これはそれらが代入演算子の左辺に出現することを意味します。右辺のオペランドは任意の式です。これは新しい値を生成して、代入により指定された変数、マトリクス要素、リターン値リストに格納されます。
変数が不変の型をもたないことに注意するのが重要です。値が何であれ、そのとき保持する型が、変数の型です。以下のプログラム断片では、変数fooは最初数値をもち、その後文字列値をもちます:
octave:13> foo = 1 foo = 1 octave:13> foo = "bar" foo = bar |
2つ目の代入によりfooに文字列値が与えられると、以前は数値をもっていたという事実は忘れられます。
インデクス付けされたマトリクスにスカラーを代入すると、インデクスにより参照されていた要素すべてにスカラー値がセットされます。たとえば、aが少なくとも2つの列をもつマトリクスの場合
a(:, 2) = 5 |
これはaに2列目の要素すべてに5をセットします。
多くに場合、空マトリクス‘[]’を割り当てることにより、マトリクスまたはベクターの行や列のすべてを削除できます。Empty Matricesを参照してください。たとえば4行5列のマトリクスAが与えられたとき、
A (3, :) = [] |
この代入により、Aの3行目が削除され、
A (:, 1:2:5) = [] |
この割り当てでは、1つ目、3つ目、5つ目の列が削除されます。
代入は式なので値をもちます。したがz = 1は式として値1をもちます。この結果、以下のように複数の代入を一緒に記述できます:
x = y = z = 0 |
これは3つの変数すべてに0をセットします。なぜならz = 0の値は0で、それがyに格納され、y = z =
0の値も0で、それがxに格納されるからです。
これはリスト値への代入でも真なので、以下は有効な式です
[a, b, c] = [u, s, v] = svd (a) |
これは以下とまったく同じです
[u, s, v] = svd (a) a = u b = s c = v |
このような式では、式の各部分の値数がマッチする必要はありません。たとえば、以下の式
[a, b] = [u, s, v] = svd (a) |
は以下と等価です
[u, s, v] = svd (a) a = u b = s |
しかし式の左辺の値の数は、右辺の値の数を超えることはできません。たとえば、以下はエラーを生成します。
[a, b, c, d] = [u, s, v] = svd (a); -| error: element number 4 undefined in return list |
シンボル~は左辺値リストの代替えとして使用され、対応するリターン値は無視され、どこにも格納されないことを示します:
[~, s, v] = svd (a); |
ダミー変数を使用することにより、より明解になり、メモリーも効率的になります。右辺の式にたいするnargoutの値は影響を受けません。代入が式として使用された場合、リターン値は無視する値が省かれたカンマ区切りリストになります。
とても一般的なプログラミングのパターンに、以下のように与えられた値による既存変数のインクリメントがあります
a = a + 2; |
以下のように+=演算子を使えば、より明解・簡略に記述できます
a += 2; |
同様な演算子は減算(-=)、乗算(*=)、除算(/=)にも存在します。以下の形式の式
expr1 op= expr2 |
は以下と等価です
expr1 = (expr1) op (expr2) |
ここで、expr2が副作用をもたないシンプルな式であれば、opは+、-、*、/のうちの1つです。expr2も代入演算子を含む場合、この式は以下のように評価されます
temp = expr2 expr1 = (expr1) op temp |
ここでtempはexpr2を評価することにより計算された一時的な値を格納するプレースホルダーです。したがって以下の式
a *= b+1 |
は以下と等価です
a = a * (b+1) |
以下のようにはなりません
a = a * b + 1 |
式が呼び出される場所ならどこでも、代入を使用できます。たとえば、yに1をセットしてからxが1と等しいかテストするために、x
!= (y =
1)と記述するのは有効です。しかし、このスタイルはプログラムの読解を難しくする傾向があります。使い捨てのプログラムを除き、このようなネストした代入を取り除くように書き直すべきです。これは難しいことではありません。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
インクリメント演算子は、変数の値を1増加または減少させます。変数を増加させる演算子は‘++’と記述します。この演算子は、変数から値を取得する前、または後のどちらかで変数を増加させるために使用します。
たとえば変数xを事前に増加させるには、++xと記述します。これはxに1加算してから、式の結果としてxの新しい値をリターンします。これは式x
= x + 1とまったく同じです。
変数xを事後に増加させるには、x++と記述します。これはxに1加算しますが、xが増加される前にもっていた値をリターンします。たとえば、xが2に等しい場合、式x++の結果は2で、xの新たな値は3になります。
マトリクスおよびベクターの引数については、インクリメントおよびデクリメント演算子はオペランドの各要素に機能します。
以下はすべてのインクリメントおよびデクリメント式のリストです。
++xこの式は、変数xをインクリメントします。式の値はxの新しい値です。これは式x =
x + 1と等価です。
--xこの式は、変数xをデクリメントします。式の値はxの新しい値です。これは式x =
x - 1と等価です。
x++この式は変数xをインクリメントします。式の値は、xの古い値です。
x--この式は、変数xをデクリメントします。式の値はxの古い値です。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
演算子の優先順位は、1つの式中に異なる演算子が近接して出現するとき、演算子がどのようにグループ化されるかを決定します。たとえば‘*’は‘+’より高い優先順位をもちます。したがって式a
+ b * cはbにcを乗じてから、その積にaを和することを意味します(例: a + (b *
c))。
カッコを使用することにより、演算子の優先順位を変更できます。優先順位は、あなたがカッコを書かなかったとき、どこにカッコがあるとみなすか告げるものと考えることができます。実際のところ、通常とは異なる演算子を組み合わせるときは常にカッコを使用するのが賢明です。なぜならプログラムを読む他の人は、この場合何が優先されるのか覚えていないかもしれないからです。あなたも同様に忘れるかもしれず、間違えるかもしれません。明示的なカッコは、そのような間違いを防ぐ助けになります。
イコール演算子の優先順位が一緒に使用された場合、最左演算子が最初にグループ化されますが、代入演算子は逆順にグループ化されます。したがって式a
- b + cは(a - b) + cとグループ化されますが、a = b = cはa = (b =
c)のようにグループ化されます。
前置単項演算子の優先順位は、オペランドの後に他の演算子が続く場合に重要です。たとえば-x^2は-(x^2)を意味します。なぜなら‘-’は‘^’より優先順位が低いからです。
以下はOctaveでの演算子を優先順位順に並べたテーブルです。しかしすべての演算子が左から右にグループ化されるわけではないことに注意してください。
関数呼び出し、および配列のインデクス操作、セル配列のインデクス操作、および構造体要素のインデクス操作‘()’ ‘{}’ ‘.’
後置インクリメント、および後置デクリメント‘++’ ‘--’
これらの演算子は右から左にグループ化されます。
転置、および指数‘'’ ‘.'’ ‘^’ ‘**’ ‘.^’ ‘.**’
単項プラス、単項マイナス、前置インクリメント、前置デクリメント、論理的"not"‘+’ ‘-’ ‘++’ ‘--’ ‘~’ ‘!’
乗算および除算‘*’ ‘/’ ‘\’ ‘.\’ ‘.*’ ‘./’
加算、減算‘+’ ‘-’
コロン‘:’
比較‘<’ ‘<=’ ‘==’ ‘>=’ ‘>’ ‘!=’ ‘~=’
要素ごとの"and"‘&’
要素ごとの"or"‘|’
論理的"and"‘&&’
論理的"or"‘||’
代入‘=’ ‘+=’ ‘-=’ ‘*=’ ‘/=’ ‘\=’ ‘^=’ ‘.*=’ ‘./=’ ‘.\=’ ‘.^=’ ‘|=’ ‘&=’
これらの演算子は右から左にグループ化されます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
式を評価するには通常、Octaveプロンプトでシンプルにそれらをタイプするか、ファイルに保存したコマンドの解釈をOctaveに命令します。
計算されて文字列に格納だれた式の評価が必要なときがあるかもしれません。それはまさにeval関数が行うことです。
文字列tryをパースして、それがOctaveプログラムであるかのように評価します。失敗した場合は、オプション文字列catchを評価します。文字列tryはカレントコンテキストで評価されるので、evalがリターンした後でも結果を利用できます。
以下はカレントワークスペースで値が約3.1416の変数Aを作成する例です。
eval ("A = acos(-1);");
|
tryを評価する間にエラーが発生した場合は、以下の例が示すようにcatch文字列が評価されます:
eval ('error ("This is a bad example");',
'printf ("This error occurred:\n%s\n", lasterr ());');
-| This error occurred:
This is a bad example
|
プログラミングノート:
evalを任意文字列の実行ではなくエラーキャプチャリングメカニズムとしてだけ使用する場合はかわりにtry/catchブロックかunwind_protect/unwind_protect_cleanupの使用を考えてください。これらのテクニックは高いパフォーマンスをもち、任意のコードを評価することによるセキュリティ問題は発生しません。
See also: evalin.
| 9.1 Calling a Function by its Name | ||
| 9.2 Evaluation in a Different Context |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
feval関数により関数名を含む文字列から関数を実行できます。これはユーザー提供関数を呼び出す必要のある関数の記述に便利です。feval関数は呼び出す関数の名前を1つ目お引数にとり、残りの引数はその関数に渡されます。
以下はfevalを使用して、ニュートン法により1変数のユーザー提供関数の根を見つける簡単な関数の例です。
function result = newtroot (fname, x)
# usage: newtroot (fname, x)
#
# fname : a string naming a function f(x).
# x : initial guess
delta = tol = sqrt (eps);
maxit = 200;
fx = feval (fname, x);
for i = 1:maxit
if (abs (fx) < tol)
result = x;
return;
else
fx_new = feval (fname, x + delta);
deriv = (fx_new - fx) / delta;
x = x - fx / deriv;
fx = fx_new;
endif
endfor
result = x;
endfunction
|
これは単にユーザー提供関数を呼び出す例を意図したもので、あまりシリアスにとるべきではないことに注意してください。さらに、より頑健なアルゴリズムを使用することにより、シリアスなコードは、提供された関数が実際に関数なのか等、すべての引数の数や型をチェックするでしょう。数値オブジェクトにたいする述語についてはPredicates for Numeric Objects、exist関数の説明はStatus of Variablesを参照してください。
nameという名前の関数を評価します。、2つ目以降の引数は、名前付き関数の入力として渡されます。たとえば、
feval ("acos", -1)
⇒ 3.1416
|
これは引数‘-1’で関数acosを呼び出します。
関数fevalは任意の種類の関数ハンドルとともに使用することもできます。歴史的に、fevalは文字列内のユーザー提供関数を呼び出す唯一の方法でしたが、現在はより明快な構文を提供する関数ハンドルが好まれます。たとえば、
f = @exp;
feval (f, 1)
⇒ 2.7183
f (1)
⇒ 2.7183
|
これは同じ方法でfにより参照される関数を呼び出します。fが関数ハンドル、文字列内の関数名、またはインライン関数なのか事前に予測できない場合は、かわりにfevalを使用してください。
ユーザースクリプトファイルを呼び出す同様の関数runもあります。スクリプトファイルはユーザーのパス上にある必要はありません。
カレントワークスペース内のscriptを実行します。
Octaveのロードパスに指定されたディレクトリに存在し、拡張子が‘".m"’のスクリプトは、単に名前をタイプして実行できます。ロードパス上にないスクリプトにたいしては、runを使用します。
ファイル名scriptはファイル名のみ、完全ファイル名または相対ファイル名で指定してもよく、拡張子を付けても付けなくても構いません。拡張子が指定されない場合、Octaveは拡張子なしのファイル名にフォールバックする前に、まず拡張子‘".m"’のスクリプトを検索します。
実装ノート:
scriptがパスコンポーネントを含む場合、runはまずscriptを探すディレクトリにディレクトリを変更します。その後runはスクリプトを実行して、元のディレクトリにリターンします。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
式を評価する前に式内で使用されている変数の値を置き換える必要があります。これらはシンボルテーブルに格納されています。インタープリターが新たに関数を開始するときは常にカレントシンボルテーブルを保存してから新しいシンボルテーブルを作成し、それを関数パラメーターのリストとnarginのような事前定義された変数を初期化します。関数内の式は、新しいシンボルテーブルを使用します。
呼び出したときに、あなたのコンテキスト内の変数を変更するような関数を記述したいときがあります。これによりCのゆなプログラミング言語でのポインター使用に似た、名前渡しスタイルの関数を使用できます。
m-filesのsaveとloadを行う関数を記述する方法を考えてみましょう。たとえば:
function create_data x = linspace (0, 10, 10); y = sin (x); save mydata x y endfunction |
evalinにより、以下のようにsaveを記述できます:
function save (file, name1, name2)
f = open_save_file (file);
save_var (f, name1, evalin ("caller", name1));
save_var (f, name2, evalin ("caller", name2));
endfunction
|
ここで‘caller’はcreate_data関数、name1はxを評価されますした値である文字列"x"です。
後で異なるコンテキストでmydataから値をloadしたい場合
function process_data load mydata … do work … endfunction |
assigninにより、以下のようにloadを記述できます:
function load (file)
f = open_load_file (file);
[name, val] = load_var (f);
assignin ("caller", name, val);
[name, val] = load_var (f);
assignin ("caller", name, val);
endfunction
|
ここで‘caller’はprocess_data関数です。
コマンドプロンプトで‘caller’ではなくコンテキスト‘base’で変数のセットおよび使用ができます。
これらの関数が実際に使用されるのはまれです。1つの例としてfail (‘code’,
‘pattern’)関数があります。これは呼び出し側のコンテキストで‘code’を評価して、与えられたパターンにマッチするエラーメッセージをチェックします。他のsaveやloadのような例はC++で記述されており、Octave変数はすべて‘caller’のコンテキストにあり、evalinは必要ありません。
式が"caller"か"base"どちらか一方のコンテキストcontextで評価されることを除外すれば、evalと同様です。
"base"か"caller"どちらか一方のコンテキストcontextで、varnameにvalueを代入します。
See also: evalin.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
命令文シンプルな定数式、ネストされたループの複雑なリスト、条件文などです。
if、whileなどの制御文は、Octaveプログラムの実行において、フロー制御を行います。制御文は、単なる式と区別するために、すべてif、whileなどの特殊キーワードで始まります。制御文の多くは他の命令文を含みます。たとえばif文は、それが実行されるか、されないかは別として、他の命令文を含みます。
制御文は、その制御文の終わりをマークするために、対応するend文をもちます。たとえば、キーワードendifはif文の終わりをマークし、endwhileはwhile文の終わりをマークします。これらの特定的なendキーワードを使える場所ではキーワードendも使うことができますが、、より特定的なキーワードを使用することにより、Octaveはendトークンのミスマッチや欠落にたいして、より良い診断情報を提供できます。
命令文のリストにはifやwhileのようなキーワードから、制御文のボディーから呼び出される対応するend命令が含まれます。
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
if文は、Octaveにおける意思決定のための命令文です。if文には、3つの形式があります。もっとも簡単なのは、以下のような形式です:
if (condition) then-body endif |
conditionは、残りの命令文が実行されるかを制御する式です。conditionがtrueのときだけ、then-bodyが実行されます。
if文中の条件は、値が非0のときはtrue、0のときはfalseと判定されます。if文中の条件式の値がベクターかマトリクスの場合は、それらが空でなく、すべての要素が非0のときだけtrueと判定されます。
if文の2つ目は以下のような形式です:
if (condition) then-body else else-body endif |
conditionがtrueのときはthen-bodyが実行され、それ以外はelse-bodyが実行されます。
以下は例です:
if (rem (x, 2) == 0)
printf ("x is even\n");
else
printf ("x is odd\n");
endif
|
この例では、式rem (x, 2) ==
0がtrue(つまりxの値が2で割り切れる)の場合は1つ目のprintf文が評価され、それ以外は2つ目のprintf文が評価されます。
if文の3つ目、そしてもっとも一般的な形式では、1つの命令文の中で、複数の判定を組み合わせることができます。これは以下のようなものです:
if (condition) then-body elseif (condition) elseif-body else else-body endif |
任意の数のelseif節を記述できます。各条件は順番にテストされ、trueになる条件が見つかったら、その条件に対応するbodyが実行されます。trueとなる条件がない場合、else節が与えられたときは、それのbodyが実行されます。else節は1つだけ記述でき、命令文の最後の部分に記述しなければなりません。
以下の例では、1つ目の条件がtrue(つまりxの値が2で割り切れる)の場合は、1つ目のprintf文が実行されます。falseの場合は2つ目の条件がテストされ、それがtrue(つまりxの値が3で割り切れる)の場合は、2つ目のprintf文が実行されます。それ以外は、3つ目のprintf文が実行されます。
if (rem (x, 2) == 0)
printf ("x is even\n");
elseif (rem (x, 3) == 0)
printf ("x is odd and divisible by 3\n");
else
printf ("x is odd\n");
endif
|
キーワードelseifは、Fortranのようにelse
ifと記述してはならないことに注意してください。そのように記述した場合、elseとifの間のスペースは、別のif文のelse節にある新たなif命令文としてそれを扱うようOctaveに指示します。たとえば、以下のように記述した場合
if (c1) body-1 else if (c2) body-2 endif |
Octave will expect additional input to complete the first if
statement. If you are using Octave interactively, it will continue to
prompt you for additional input. If Octave is reading this input from a
file, it may complain about missing or mismatched end statements, or,
if you have not used the more specific end statements (endif,
endfor, etc.), it may simply produce incorrect results, without
producing any warning messages.
It is much easier to see the error if we rewrite the statements above like this,
if (c1)
body-1
else
if (c2)
body-2
endif
|
using the indentation to show how Octave groups the statements. See section Functions and Scripts.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
It is very common to take different actions depending on the value of one
variable. This is possible using the if statement in the following
way
if (X == 1) do_something (); elseif (X == 2) do_something_else (); else do_something_completely_different (); endif |
This kind of code can however be very cumbersome to both write and
maintain. To overcome this problem Octave supports the switch
statement. Using this statement, the above example becomes
switch (X)
case 1
do_something ();
case 2
do_something_else ();
otherwise
do_something_completely_different ();
endswitch
|
This code makes the repetitive structure of the problem more explicit,
making the code easier to read, and hence maintain. Also, if the variable
X should change its name, only one line would need changing compared
to one line per case when if statements are used.
The general form of the switch statement is
switch (expression)
case label
command_list
case label
command_list
…
otherwise
command_list
endswitch
|
where label can be any expression. However, duplicate label
values are not detected, and only the command_list corresponding to
the first match will be executed. For the switch statement to be
meaningful at least one case label command_list clause
must be present, while the otherwise command_list clause is
optional.
If label is a cell array the corresponding command_list is executed if any of the elements of the cell array match expression. As an example, the following program will print ‘Variable is either 6 or 7’.
A = 7;
switch (A)
case { 6, 7 }
printf ("variable is either 6 or 7\n");
otherwise
printf ("variable is neither 6 nor 7\n");
endswitch
|
As with all other specific end keywords, endswitch may be
replaced by end, but you can get better diagnostics if you use the
specific forms.
One advantage of using the switch statement compared to using
if statements is that the labels can be strings. If an
if statement is used it is not possible to write
if (X == "a string") # This is NOT valid |
since a character-to-character comparison between X and the string
will be made instead of evaluating if the strings are equal. This
special-case is handled by the switch statement, and it is possible
to write programs that look like this
switch (X)
case "a string"
do_something
…
endswitch
|
| 10.2.1 Notes for the C Programmer |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The switch statement is also available in the widely used C
programming language. There are, however, some differences between the
statement in Octave and C
switch statement of the C language.
switch (foo) case (1) -2 … |
would produce surprising results, as would
switch (foo)
case (1)
case (2)
doit ();
…
|
particularly for C programmers. If doit() should be executed if
foo is either 1 or 2, the above code should be written
with a cell array like this
switch (foo)
case { 1, 2 }
doit ();
…
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In programming, a loop means a part of a program that is (or at least can be) executed two or more times in succession.
The while statement is the simplest looping statement in Octave. It
repeatedly executes a statement as long as a condition is true. As with the
condition in an if statement, the condition in a while
statement is considered true if its value is non-zero, and false if its
value is zero. If the value of the conditional expression in a while
statement is a vector or a matrix, it is considered true only if it is
non-empty and all of the elements are non-zero.
Octave’s while statement looks like this:
while (condition) body endwhile |
Here body is a statement or list of statements that we call the body of the loop, and condition is an expression that controls how long the loop keeps running.
The first thing the while statement does is test condition. If
condition is true, it executes the statement body. After
body has been executed, condition is tested again, and if it is
still true, body is executed again. This process repeats until
condition is no longer true. If condition is initially false,
the body of the loop is never executed.
This example creates a variable fib that contains the first ten
elements of the Fibonacci sequence.
fib = ones (1, 10); i = 3; while (i <= 10) fib (i) = fib (i-1) + fib (i-2); i++; endwhile |
Here the body of the loop contains two statements.
The loop works like this: first, the value of i is set to 3. Then,
the while tests whether i is less than or equal to 10. This
is the case when i equals 3, so the value of the i-th element
of fib is set to the sum of the previous two values in the sequence.
Then the i++ increments the value of i and the loop repeats.
The loop terminates when i reaches 11.
A newline is not required between the condition and the body; but using one makes the program clearer unless the body is very simple.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The do-until statement is similar to the while statement,
except that it repeatedly executes a statement until a condition becomes
true, and the test of the condition is at the end of the loop, so the body
of the loop is always executed at least once. As with the condition in an
if statement, the condition in a do-until statement is
considered true if its value is non-zero, and false if its value is zero.
If the value of the conditional expression in a do-until statement is
a vector or a matrix, it is considered true only if it is non-empty and
all of the elements are non-zero.
Octave’s do-until statement looks like this:
do body until (condition) |
Here body is a statement or list of statements that we call the body of the loop, and condition is an expression that controls how long the loop keeps running.
This example creates a variable fib that contains the first ten
elements of the Fibonacci sequence.
fib = ones (1, 10); i = 2; do i++; fib (i) = fib (i-1) + fib (i-2); until (i == 10) |
A newline is not required between the do keyword and the body; but
using one makes the program clearer unless the body is very simple.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The for statement makes it more convenient to count iterations of a
loop. The general form of the for statement looks like this:
for var = expression body endfor |
where body stands for any statement or list of statements, expression is any valid expression, and var may take several forms. Usually it is a simple variable name or an indexed variable. If the value of expression is a structure, var may also be a vector with two elements. See section Looping Over Structure Elements, below.
The assignment expression in the for statement works a bit
differently than Octave’s normal assignment statement. Instead of assigning
the complete result of the expression, it assigns each column of the
expression to var in turn. If expression is a range, a row
vector, or a scalar, the value of var will be a scalar each time the
loop body is executed. If var is a column vector or a matrix,
var will be a column vector each time the loop body is executed.
The following example shows another way to create a vector containing the
first ten elements of the Fibonacci sequence, this time using the for
statement:
fib = ones (1, 10); for i = 3:10 fib (i) = fib (i-1) + fib (i-2); endfor |
This code works by first evaluating the expression 3:10, to produce a
range of values from 3 to 10 inclusive. Then the variable i is
assigned the first element of the range and the body of the loop is executed
once. When the end of the loop body is reached, the next value in the range
is assigned to the variable i, and the loop body is executed again.
This process continues until there are no more elements to assign.
Within Octave is it also possible to iterate over matrices or cell arrays
using the for statement. For example consider
disp ("Loop over a matrix")
for i = [1,3;2,4]
i
endfor
disp ("Loop over a cell array")
for i = {1,"two";"three",4}
i
endfor
|
In this case the variable i takes on the value of the columns of the
matrix or cell matrix. So the first loop iterates twice, producing two
column vectors [1;2], followed by [3;4], and likewise for the
loop over the cell array. This can be extended to loops over
multi-dimensional arrays. For example:
a = [1,3;2,4]; c = cat (3, a, 2*a); for i = c i endfor |
In the above case, the multi-dimensional matrix c is reshaped to a
two-dimensional matrix as reshape (c, rows (c), prod (size
(c)(2:end))) and then the same behavior as a loop over a two dimensional
matrix is produced.
Although it is possible to rewrite all for loops as while
loops, the Octave language has both statements because often a for
loop is both less work to type and more natural to think of. Counting the
number of iterations is very common in loops and it can be easier to think
of this counting as part of looping rather than as something to do inside
the loop.
| 10.5.1 Looping Over Structure Elements |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A special form of the for statement allows you to loop over all the
elements of a structure:
for [ val, key ] = expression body endfor |
In this form of the for statement, the value of expression must
be a structure. If it is, key and val are set to the name of
the element and the corresponding value in turn, until there are no more
elements. For example:
x.a = 1
x.b = [1, 2; 3, 4]
x.c = "string"
for [val, key] = x
key
val
endfor
-| key = a
-| val = 1
-| key = b
-| val =
-|
-| 1 2
-| 3 4
-|
-| key = c
-| val = string
|
The elements are not accessed in any particular order. If you need to cycle
through the list in a particular way, you will have to use the function
fieldnames and sort the list yourself.
The key variable may also be omitted. If it is, the brackets are also optional. This is useful for cycling through the values of all the structure elements when the names of the elements do not need to be known.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The break statement jumps out of the innermost while,
do-until, or for loop that encloses it. The break
statement may only be used within the body of a loop. The following example
finds the smallest divisor of a given integer, and also identifies prime
numbers:
num = 103;
div = 2;
while (div*div <= num)
if (rem (num, div) == 0)
break;
endif
div++;
endwhile
if (rem (num, div) == 0)
printf ("Smallest divisor of %d is %d\n", num, div)
else
printf ("%d is prime\n", num);
endif
|
When the remainder is zero in the first while statement, Octave
immediately breaks out of the loop. This means that Octave proceeds
immediately to the statement following the loop and continues processing.
(This is very different from the exit statement which stops the
entire Octave program.)
Here is another program equivalent to the previous one. It illustrates how
the condition of a while statement could just as well be
replaced with a break inside an if:
num = 103;
div = 2;
while (1)
if (rem (num, div) == 0)
printf ("Smallest divisor of %d is %d\n", num, div);
break;
endif
div++;
if (div*div > num)
printf ("%d is prime\n", num);
break;
endif
endwhile
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The continue statement, like break, is used only inside
while, do-until, or for loops. It skips over the rest
of the loop body, causing the next cycle around the loop to begin
immediately. Contrast this with break, which jumps out of the loop
altogether. Here is an example:
# print elements of a vector of random
# integers that are even.
# first, create a row vector of 10 random
# integers with values between 0 and 100:
vec = round (rand (1, 10) * 100);
# print what we're interested in:
for x = vec
if (rem (x, 2) != 0)
continue;
endif
printf ("%d\n", x);
endfor
|
If one of the elements of vec is an odd number, this example skips the print statement for that element, and continues back to the first statement in the loop.
This is not a practical example of the continue statement, but it
should give you a clear understanding of how it works. Normally, one would
probably write the loop like this:
for x = vec
if (rem (x, 2) == 0)
printf ("%d\n", x);
endif
endfor
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave supports a limited form of exception handling modeled after the unwind-protect form of Lisp.
The general form of an unwind_protect block looks like this:
unwind_protect body unwind_protect_cleanup cleanup end_unwind_protect |
where body and cleanup are both optional and may contain any Octave expressions or commands. The statements in cleanup are guaranteed to be executed regardless of how control exits body.
This is useful to protect temporary changes to global variables from
possible errors. For example, the following code will always restore the
original value of the global variable frobnosticate even if an error
occurs in the first part of the unwind_protect block.
save_frobnosticate = frobnosticate; unwind_protect frobnosticate = true; … unwind_protect_cleanup frobnosticate = save_frobnosticate; end_unwind_protect |
Without unwind_protect, the value of frobnosticate would not be
restored if an error occurs while evaluating the first part of the
unwind_protect block because evaluation would stop at the point of
the error and the statement to restore the value would not be executed.
In addition to unwind_protect, Octave supports another form of exception
handling, the try block.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The original form of a try block looks like this:
try body catch cleanup end_try_catch |
where body and cleanup are both optional and may contain any Octave expressions or commands. The statements in cleanup are only executed if an error occurs in body.
No warnings or error messages are printed while body is executing. If
an error does occur during the execution of body, cleanup can
use the functions lasterr or lasterror to access the text of
the message that would have been printed, as well as its identifier. The
alternative form,
try body catch err cleanup end_try_catch |
will automatically store the output of lasterror in the structure
err. See section Errors and Warnings, for more information about the
lasterr and lasterror functions.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In the Octave language, most statements end with a newline character and you
must tell Octave to ignore the newline character in order to continue a
statement from one line to the next. Lines that end with the characters
... are joined with the following line before they are divided into
tokens by Octave’s parser. For example, the lines
x = long_variable_name ...
+ longer_variable_name ...
- 42
|
form a single statement.
Any text between the continuation marker and the newline character is ignored. For example, the statement
x = long_variable_name ... # comment one
+ longer_variable_name ...comment two
- 42 # last comment
|
is equivalent to the one shown above.
Inside double-quoted string constants, the character \ has to be used
as continuation marker. The \ must appear at the end of the line
just before the newline character:
s = "This text starts in the first line \ and is continued in the second line." |
Input that occurs inside parentheses can be continued to the next line without having to use a continuation marker. For example, it is possible to write statements like
if (fine_dining_destination == on_a_boat
|| fine_dining_destination == on_a_train)
seuss (i, will, not, eat, them, sam, i, am, i,
will, not, eat, green, eggs, and, ham);
endif
|
without having to add to the clutter with continuation markers.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Complicated Octave programs can often be simplified by defining functions. Functions can be defined directly on the command line during interactive Octave sessions, or in external files, and can be called just like built-in functions.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There are seven different things covered in this section.
Both function files and script files end with an extension of .m, for MATLAB compatibility. If you want more than one independent functions in a file, it must be a script file (see section Script Files), and to use these functions you must execute the script file before you can use the functions that are in the script file.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In its simplest form, the definition of a function named name looks like this:
function name body endfunction |
A valid function name is like a valid variable name: a sequence of letters, digits and underscores, not starting with a digit. Functions share the same pool of names as variables.
The function body consists of Octave statements. It is the most important part of the definition, because it says what the function should actually do.
For example, here is a function that, when executed, will ring the bell on your terminal (assuming that it is possible to do so):
function wakeup
printf ("\a");
endfunction
|
The printf statement (see section Input and Output) simply tells
Octave to print the string "a". The special character ‘\a’
stands for the alert character (ASCII 7). See section Strings.
Once this function is defined, you can ask Octave to evaluate it by typing the name of the function.
Normally, you will want to pass some information to the functions you define. The syntax for passing parameters to a function in Octave is
function name (arg-list) body endfunction |
where arg-list is a comma-separated list of the function’s arguments. When the function is called, the argument names are used to hold the argument values given in the call. The list of arguments may be empty, in which case this form is equivalent to the one shown above.
To print a message along with ringing the bell, you might modify the
wakeup to look like this:
function wakeup (message)
printf ("\a%s\n", message);
endfunction
|
Calling this function using a statement like this
wakeup ("Rise and shine!");
|
will cause Octave to ring your terminal’s bell and print the message
‘Rise and shine!’, followed by a newline character (the ‘\n’
in the first argument to the printf statement).
In most cases, you will also want to get some information back from the functions you define. Here is the syntax for writing a function that returns a single value:
function ret-var = name (arg-list) body endfunction |
The symbol ret-var is the name of the variable that will hold the value to be returned by the function. This variable must be defined before the end of the function body in order for the function to return a value.
Variables used in the body of a function are local to the function. Variables named in arg-list and ret-var are also local to the function. See section Global Variables, for information about how to access global variables inside a function.
For example, here is a function that computes the average of the elements of a vector:
function retval = avg (v) retval = sum (v) / length (v); endfunction |
If we had written avg like this instead,
function retval = avg (v)
if (isvector (v))
retval = sum (v) / length (v);
endif
endfunction
|
and then called the function with a matrix instead of a vector as the argument, Octave would have printed an error message like this:
error: value on right hand side of assignment is undefined |
because the body of the if statement was never executed, and
retval was never defined. To prevent obscure errors like this,
it is a good idea to always make sure that the return variables will
always have values, and to produce meaningful error messages when
problems are encountered. For example, avg could have been
written like this:
function retval = avg (v)
retval = 0;
if (isvector (v))
retval = sum (v) / length (v);
else
error ("avg: expecting vector argument");
endif
endfunction
|
There is still one additional problem with this function. What if it is
called without an argument? Without additional error checking, Octave
will probably print an error message that won’t really help you track
down the source of the error. To allow you to catch errors like this,
Octave provides each function with an automatic variable called
nargin. Each time a function is called, nargin is
automatically initialized to the number of arguments that have actually
been passed to the function. For example, we might rewrite the
avg function like this:
function retval = avg (v)
retval = 0;
if (nargin != 1)
usage ("avg (vector)");
endif
if (isvector (v))
retval = sum (v) / length (v);
else
error ("avg: expecting vector argument");
endif
endfunction
|
Although Octave does not automatically report an error if you call a function with more arguments than expected, doing so probably indicates that something is wrong. Octave also does not automatically report an error if a function is called with too few arguments, but any attempt to use a variable that has not been given a value will result in an error. To avoid such problems and to provide useful messages, we check for both possibilities and issue our own error message.
Within a function, return the number of arguments passed to the function. At the top level, return the number of command line arguments passed to Octave.
If called with the optional argument fcn—a function name or handle— return the declared number of arguments that the function can accept.
If the last argument to fcn is varargin the returned value is
negative. For example, the function union for sets is declared as
function [y, ia, ib] = union (a, b, varargin)
and
nargin ("union")
⇒ -3
|
Programming Note: nargin does not work on built-in functions.
See also: nargout, varargin, isargout, varargout, nthargout.
Return the name of the n-th argument to the calling function. If the argument is not a simple variable name, return an empty string.
Query or set the internal variable that controls whether internal output from a function is suppressed. If this option is disabled, Octave will display the results produced by evaluating expressions within a function body that are not terminated with a semicolon.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Unlike many other computer languages, Octave allows you to define functions that return more than one value. The syntax for defining functions that return multiple values is
function [ret-list] = name (arg-list) body endfunction |
where name, arg-list, and body have the same meaning
as before, and ret-list is a comma-separated list of variable
names that will hold the values returned from the function. The list of
return values must have at least one element. If ret-list has
only one element, this form of the function statement is
equivalent to the form described in the previous section.
Here is an example of a function that returns two values, the maximum element of a vector and the index of its first occurrence in the vector.
function [max, idx] = vmax (v)
idx = 1;
max = v (idx);
for i = 2:length (v)
if (v (i) > max)
max = v (i);
idx = i;
endif
endfor
endfunction
|
In this particular case, the two values could have been returned as elements of a single array, but that is not always possible or convenient. The values to be returned may not have compatible dimensions, and it is often desirable to give the individual return values distinct names.
It is possible to use the nthargout function to obtain only some
of the return values or several at once in a cell array.
See section Cell Array Objects.
Return the nth output argument of function given by the function handle or string func. Any arguments after func are passed to func. The total number of arguments to call func with can be passed in ntot; by default ntot is n. The input n can also be a vector of indices of the output, in which case the output will be a cell array of the requested output arguments.
The intended use nthargout is to avoid intermediate variables.
For example, when finding the indices of the maximum entry of a
matrix, the following two compositions of nthargout
m = magic (5);
cell2mat (nthargout ([1, 2], @ind2sub, size (m),
nthargout (2, @max, m(:))))
⇒ 5 3
|
are completely equivalent to the following lines:
m = magic (5); [~, idx] = max (M(:)); [i, j] = ind2sub (size (m), idx); [i, j] ⇒ 5 3 |
It can also be helpful to have all output arguments in a single cell in the following manner:
USV = nthargout ([1:3], @svd, hilb (5)); |
In addition to setting nargin each time a function is called,
Octave also automatically initializes nargout to the number of
values that are expected to be returned. This allows you to write
functions that behave differently depending on the number of values that
the user of the function has requested. The implicit assignment to the
built-in variable ans does not figure in the count of output
arguments, so the value of nargout may be zero.
The svd and lu functions are examples of built-in
functions that behave differently depending on the value of
nargout.
It is possible to write functions that only set some return values. For example, calling the function
function [x, y, z] = f () x = 1; z = 2; endfunction |
as
[a, b, c] = f () |
produces:
a = 1 b = [](0x0) c = 2 |
along with a warning.
Within a function, return the number of values the caller expects to receive. If called with the optional argument fcn—a function name or handle—return the number of declared output values that the function can produce. If the final output argument is varargout the returned value is negative.
For example,
f () |
will cause nargout to return 0 inside the function f and
[s, t] = f () |
will cause nargout to return 2 inside the function f.
In the second usage,
nargout (@histc) % or nargout ("histc")
|
will return 2, because histc has two outputs, whereas
nargout (@imread) |
will return -2, because imread has two outputs and the second is
varargout.
At the top level, nargout with no argument is undefined and will
produce an error. nargout does not work for built-in functions and
returns -1 for all anonymous functions.
It is good practice at the head of a function to verify that it has been called correctly. In Octave the following idiom is seen frequently
if (nargin < min_#_inputs || nargin > max_#_inputs) print_usage (); endif |
which stops the function execution and prints a message about the correct way to call the function whenever the number of inputs is wrong.
For compatibility with MATLAB, nargchk, narginchk and
nargoutchk are available which provide similar error checking.
Return an appropriate error message string (or structure) if the number of inputs requested is invalid.
This is useful for checking to see that the number of input arguments supplied to a function is within an acceptable range.
See also: nargoutchk, narginchk, error, nargin, nargout.
Check for correct number of arguments or generate an error message if the number of arguments in the calling function is outside the range minargs and maxargs. Otherwise, do nothing.
Both minargs and maxargs need to be scalar numeric values. Zero, Inf and negative values are all allowed, and minargs and maxargs may be equal.
Note that this function evaluates nargin on the caller.
See also: nargchk, nargoutchk, error, nargout, nargin.
Check for correct number of output arguments.
On the first form, returns an error unless the number of arguments in its
caller is between the values of minargs and maxargs. It does
nothing otherwise. Note that this function evaluates the value of
nargout on the caller so its value must have not been tampered with.
Both minargs and maxargs need to be a numeric scalar. Zero, Inf and negative are all valid, and they can have the same value.
For backward compatibility reasons, the other forms return an appropriate error message string (or structure) if the number of outputs requested is invalid.
This is useful for checking to see that the number of output arguments supplied to a function is within an acceptable range.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Sometimes the number of input arguments is not known when the function is defined. As an example think of a function that returns the smallest of all its input arguments. For example:
a = smallest (1, 2, 3); b = smallest (1, 2, 3, 4); |
In this example both a and b would be 1. One way to write
the smallest function is
function val = smallest (arg1, arg2, arg3, arg4, arg5) body endfunction |
and then use the value of nargin to determine which of the input
arguments should be considered. The problem with this approach is
that it can only handle a limited number of input arguments.
If the special parameter name varargin appears at the end of a
function parameter list it indicates that the function takes a variable
number of input arguments. Using varargin the function
looks like this
function val = smallest (varargin) body endfunction |
In the function body the input arguments can be accessed through the
variable varargin. This variable is a cell array containing
all the input arguments. See section Cell Arrays, for details on working
with cell arrays. The smallest function can now be defined
like this
function val = smallest (varargin)
val = min ([varargin{:}]);
endfunction
|
This implementation handles any number of input arguments, but it’s also a very simple solution to the problem.
A slightly more complex example of varargin is a function
print_arguments that prints all input arguments. Such a function
can be defined like this
function print_arguments (varargin)
for i = 1:length (varargin)
printf ("Input argument %d: ", i);
disp (varargin{i});
endfor
endfunction
|
This function produces output like this
print_arguments (1, "two", 3);
-| Input argument 1: 1
-| Input argument 2: two
-| Input argument 3: 3
|
Return in reg the cell elements of param up to the first string element and in prop all remaining elements beginning with the first string element. For example:
[reg, prop] = parseparams ({1, 2, "linewidth", 10})
reg =
{
[1,1] = 1
[1,2] = 2
}
prop =
{
[1,1] = linewidth
[1,2] = 10
}
|
The parseparams function may be used to separate regular numeric arguments from additional arguments given as property/value pairs of the varargin cell array.
In the second form of the call, available options are specified directly with their default values given as name-value pairs. If params do not form name-value pairs, or if an option occurs that does not match any of the available options, an error occurs. When called from an m-file function, the error is prefixed with the name of the caller function. The matching of options is case-insensitive.
See also: varargin.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In the formal argument list, it is possible to use the dummy placeholder
~ instead of a name. This indicates that the corresponding argument
value should be ignored and not stored to any variable.
function val = pick2nd (~, arg2) val = arg2; endfunction |
The value of nargin is not affected by using this declaration.
Return arguments can also be ignored using the same syntax. Functions may
take advantage of ignored outputs to reduce the number of calculations
performed. To do so, use the isargout function to query whether the
output argument is wanted. For example:
function [out1, out2] = long_function (x, y, z)
if (isargout (1))
## Long calculation
…
out1 = result;
endif
…
endfunction
|
Within a function, return a logical value indicating whether the argument
k will be assigned to a variable on output. If the result is false,
the argument has been ignored during the function call through the use of
the tilde (~) special output argument. Functions can use isargout to
avoid performing unnecessary calculations for outputs which are unwanted.
If k is outside the range 1:max (nargout), the function returns
false. k can also be an array, in which case the function works
element-by-element and a logical array is returned. At the top level,
isargout returns an error.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
It is possible to return a variable number of output arguments from a
function using a syntax that’s similar to the one used with the
special varargin parameter name. To let a function return a
variable number of output arguments the special output parameter name
varargout is used. As with varargin, varargout is
a cell array that will contain the requested output arguments.
As an example the following function sets the first output argument to 1, the second to 2, and so on.
function varargout = one_to_n ()
for i = 1:nargout
varargout{i} = i;
endfor
endfunction
|
When called this function returns values like this
[a, b, c] = one_to_n ()
⇒ a = 1
⇒ b = 2
⇒ c = 3
|
If varargin (varargout) does not appear as the last
element of the input (output) parameter list, then it is not special,
and is handled the same as any other parameter name.
Copy the input parameters into the corresponding output parameters. If only one input parameter is supplied, its value is copied to each of the outputs.
For example,
[a, b, c] = deal (x, y, z); |
is equivalent to
a = x; b = y; c = z; |
and
[a, b, c] = deal (x); |
is equivalent to
a = b = c = x; |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The body of a user-defined function can contain a return statement.
This statement returns control to the rest of the Octave program. It
looks like this:
return |
Unlike the return statement in C, Octave’s return
statement cannot be used to return a value from a function. Instead,
you must assign values to the list of return variables that are part of
the function statement. The return statement simply makes
it easier to exit a function from a deeply nested loop or conditional
statement.
Here is an example of a function that checks to see if any elements of a vector are nonzero.
function retval = any_nonzero (v)
retval = 0;
for i = 1:length (v)
if (v (i) != 0)
retval = 1;
return;
endif
endfor
printf ("no nonzero elements found\n");
endfunction
|
Note that this function could not have been written using the
break statement to exit the loop once a nonzero value is found
without adding extra logic to avoid printing the message if the vector
does contain a nonzero element.
When Octave encounters the keyword return inside a function or
script, it returns control to the caller immediately. At the top level,
the return statement is ignored. A return statement is assumed
at the end of every function definition.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Since Octave supports variable number of input arguments, it is very useful to assign default values to some input arguments. When an input argument is declared in the argument list it is possible to assign a default value to the argument like this
function name (arg1 = val1, …) body endfunction |
If no value is assigned to arg1 by the user, it will have the value val1.
As an example, the following function implements a variant of the classic “Hello, World” program.
function hello (who = "World")
printf ("Hello, %s!\n", who);
endfunction
|
When called without an input argument the function prints the following
hello ();
-| Hello, World!
|
and when it’s called with an input argument it prints the following
hello ("Beautiful World of Free Software");
-| Hello, Beautiful World of Free Software!
|
Sometimes it is useful to explicitly tell Octave to use the default value of an input argument. This can be done writing a ‘:’ as the value of the input argument when calling the function.
hello (:);
-| Hello, World!
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Except for simple one-shot programs, it is not practical to have to define all the functions you need each time you need them. Instead, you will normally want to save them in a file so that you can easily edit them, and save them for use at a later time.
Octave does not require you to load function definitions from files before using them. You simply need to put the function definitions in a place where Octave can find them.
When Octave encounters an identifier that is undefined, it first looks for variables or functions that are already compiled and currently listed in its symbol table. If it fails to find a definition there, it searches a list of directories (the path) for files ending in ‘.m’ that have the same base name as the undefined identifier.(5) Once Octave finds a file with a name that matches, the contents of the file are read. If it defines a single function, it is compiled and executed. See section Script Files, for more information about how you can define more than one function in a single file.
When Octave defines a function from a function file, it saves the full name of the file it read and the time stamp on the file. If the time stamp on the file changes, Octave may reload the file. When Octave is running interactively, time stamp checking normally happens at most once each time Octave prints the prompt. Searching for new function definitions also occurs if the current working directory changes.
Checking the time stamp allows you to edit the definition of a function while Octave is running, and automatically use the new function definition without having to restart your Octave session.
To avoid degrading performance unnecessarily by checking the time stamps on functions that are not likely to change, Octave assumes that function files in the directory tree ‘octave-home/share/octave/version/m’ will not change, so it doesn’t have to check their time stamps every time the functions defined in those files are used. This is normally a very good assumption and provides a significant improvement in performance for the function files that are distributed with Octave.
If you know that your own function files will not change while you are
running Octave, you can improve performance by calling
ignore_function_time_stamp ("all"), so that Octave will
ignore the time stamps for all function files. Passing
"system" to this function resets the default behavior.
Edit the named function, or change editor settings.
If edit is called with the name of a file or function as
its argument it will be opened in the text editor defined by EDITOR.
HOME (see below) and then edited.
If no file is found, then the m-file
variant, ending with ".m", will be considered. If still no file
is found, then variants with a leading "@" and then with both a
leading "@" and trailing ".m" will be considered.
HOME
to contain that function along with its current definition.
name.cc is specified, then it will search for
name.cc in the path and try to modify it, otherwise it will
create a new ‘.cc’ file in the current directory. If name happens
to be an m-file or interpreter defined function, then the text of that
function will be inserted into the .cc file as a comment.
HOME before editing.
Warning: You may need to clear name before the new definition
is available. If you are editing a .cc file, you will need
to execute mkoctfile ‘name.cc’ before the definition
will be available.
If edit is called with field and value variables,
the value of the control field field will be set to value.
If an output argument is requested and the first input argument is get
then edit will return the value of the control field field.
If the control field does not exist, edit will return a structure
containing all fields and values. Thus, edit get all returns
a complete control structure.
The following control fields are used:
This is the location of user local m-files. Be sure it is in your path. The default is ‘~/octave’.
This is the name to put after the "## Author:" field of new functions.
By default it guesses from the gecos field of the password database.
This is the e-mail address to list after the name in the author field.
By default it guesses <$LOGNAME@$HOSTNAME>, and if $HOSTNAME
is not defined it uses uname -n. You probably want to override this.
Be sure to use the format <user@host>.
GNU General Public License (default).
BSD-style license without advertising clause.
Public domain.
Your own default copyright and license.
Unless you specify ‘pd’, edit will prepend the copyright statement with "Copyright (C) yyyy Function Author".
This value determines whether the editor should be started in async mode
(editor is started in the background and Octave continues) or sync mode
(Octave waits until the editor exits). Set it to "sync" to start
the editor in sync mode. The default is "async"
(see system).
Determines whether files should be edited in place, without regard to
whether they are modifiable or not. The default is false.
Return the name of the currently executing file.
When called from outside an m-file return the empty string. Given the
argument "fullpath", include the directory part of the file name,
but not the extension. Given the argument "fullpathext", include
the directory part of the file name and the extension.
Query or set the internal variable that controls whether Octave checks
the time stamp on files each time it looks up functions defined in
function files. If the internal variable is set to "system",
Octave will not automatically recompile function files in subdirectories of
‘octave-home/lib/version’ if they have changed since
they were last compiled, but will recompile other function files in the
search path if they change. If set to "all", Octave will not
recompile any function files unless their definitions are removed with
clear. If set to "none", Octave will always check time
stamps on files to determine whether functions defined in function files
need to recompiled.
| 11.9.1 Manipulating the Load Path | ||
| 11.9.2 Subfunctions | ||
| 11.9.3 Private Functions | ||
| 11.9.4 Nested Functions | ||
| 11.9.5 Overloading and Autoloading | ||
| 11.9.6 Function Locking | ||
| 11.9.7 Function Precedence |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
When a function is called, Octave searches a list of directories for
a file that contains the function declaration. This list of directories
is known as the load path. By default the load path contains
a list of directories distributed with Octave plus the current
working directory. To see your current load path call the path
function without any input or output arguments.
It is possible to add or remove directories to or from the load path
using addpath and rmpath. As an example, the following
code adds ‘~/Octave’ to the load path.
addpath ("~/Octave")
|
After this the directory ‘~/Octave’ will be searched for functions.
Add named directories to the function search path. If
option is "-begin" or 0 (the default), prepend the
directory name to the current path. If option is "-end"
or 1, append the directory name to the current path.
Directories added to the path must exist.
In addition to accepting individual directory arguments, lists of
directory names separated by pathsep are also accepted. For example:
addpath ("dir1:/dir2:~/dir3")
|
See also: path, rmpath, genpath, pathdef, savepath, pathsep.
Return a path constructed from dir and all its subdirectories. If additional string parameters are given, the resulting path will exclude directories with those names.
Remove dir1, … from the current function search path.
In addition to accepting individual directory arguments, lists of
directory names separated by pathsep are also accepted. For example:
rmpath ("dir1:/dir2:~/dir3")
|
See also: path, addpath, genpath, pathdef, savepath, pathsep.
Save the unique portion of the current function search path that is
not set during Octave’s initialization process to file.
If file is omitted, ‘~/.octaverc’ is used. If successful,
savepath returns 0.
Modify or display Octave’s load path.
If nargin and nargout are zero, display the elements of Octave’s load path in an easy to read format.
If nargin is zero and nargout is greater than zero, return the current load path.
If nargin is greater than zero, concatenate the arguments,
separating them with pathsep. Set the internal search path
to the result and return it.
No checks are made for duplicate elements.
See also: addpath, rmpath, genpath, pathdef, savepath, pathsep.
Return the default path for Octave. The path information is extracted from one of three sources. The possible sources, in order of preference, are:
Query or set the character used to separate directories in a path.
See also: filesep.
Reinitialize Octave’s load path directory cache.
Return the absolute name of file if it can be found in
the list of directories specified by path.
If no file is found, return an empty character string.
If the first argument is a cell array of strings, search each directory of the loadpath for element of the cell array and return the first that matches.
If the second optional argument "all" is supplied, return
a cell array containing the list of all files that have the same
name in the path. If no files are found, return an empty cell array.
See also: file_in_path, find_dir_in_path, path.
Restore Octave’s path to its initial state at startup.
See also: path, addpath, rmpath, genpath, pathdef, savepath, pathsep.
Return the command line path variable.
See also: path, addpath, rmpath, genpath, pathdef, savepath, pathsep.
Return the full name of the path element matching dir. The
match is performed at the end of each path element. For example, if
dir is "foo/bar", it matches the path element
"/some/dir/foo/bar", but not
"/some/dir/foo/bar/baz"
"/some/dir/allfoo/bar".
The second argument is optional. If it is supplied, return a cell array containing all name matches rather than just the first.
See also: file_in_path, file_in_loadpath, path.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A function file may contain secondary functions called subfunctions. These secondary functions are only visible to the other functions in the same function file. For example, a file ‘f.m’ containing
function f ()
printf ("in f, calling g\n");
g ()
endfunction
function g ()
printf ("in g, calling h\n");
h ()
endfunction
function h ()
printf ("in h\n")
endfunction
|
defines a main function f and two subfunctions. The
subfunctions g and h may only be called from the main
function f or from the other subfunctions, but not from outside
the file ‘f.m’.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In many cases one function needs to access one or more helper functions. If the helper function is limited to the scope of a single function, then subfunctions as discussed above might be used. However, if a single helper function is used by more than one function, then this is no longer possible. In this case the helper functions might be placed in a subdirectory, called "private", of the directory in which the functions needing access to this helper function are found.
As a simple example, consider a function func1, that calls a helper
function func2 to do much of the work. For example:
function y = func1 (x) y = func2 (x); endfunction |
Then if the path to func1 is <directory>/func1.m, and if
func2 is found in the directory <directory>/private/func2.m,
then func2 is only available for use of the functions, like
func1, that are found in <directory>.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Nested functions are similar to subfunctions in that only the main function is visible outside the file. However, they also allow for child functions to access the local variables in their parent function. This shared access mimics using a global variable to share information — but a global variable which is not visible to the rest of Octave. As a programming strategy, sharing data this way can create code which is difficult to maintain. It is recommended to use subfunctions in place of nested functions when possible.
As a simple example, consider a parent function foo, that calls a nested
child function bar, with a shared variable x.
function y = foo ()
x = 10;
bar ();
y = x;
function bar ()
x = 20;
endfunction
endfunction
foo ()
⇒ 20
|
Notice that there is no special syntax for sharing x. This can lead to problems with accidental variable sharing between a parent function and its child. While normally variables are inherited, child function parameters and return values are local to the child function.
Now consider the function foobar that uses variables x and
y. foobar calls a nested function foo which takes
x as a parameter and returns y. foo then calls bat
which does some computation.
function z = foobar ()
x = 0;
y = 0;
z = foo (5);
z += x + y;
function y = foo (x)
y = x + bat ();
function z = bat ()
z = x;
endfunction
endfunction
endfunction
foobar ()
⇒ 10
|
It is important to note that the x and y in foobar remain
zero, as in foo they are a return value and parameter respectively. The
x in bat refers to the x in foo.
Variable inheritance leads to a problem for eval and scripts. If a
new variable is created in a parent function, it is not clear what should happen
in nested child functions. For example, consider a parent function foo
with a nested child function bar:
function y = foo (to_eval)
bar ();
eval (to_eval);
function bar ()
eval ("x = 100;");
eval ("y = x;");
endfunction
endfunction
foo ("x = 5;")
⇒ error: can not add variable "x" to a static workspace
foo ("y = 10;")
⇒ 10
foo ("")
⇒ 100
|
The parent function foo is unable to create a new variable
x, but the child function bar was successful. Furthermore, even
in an eval statement y in bar is the same y as in its
parent function foo. The use of eval in conjunction with nested
functions is best avoided.
As with subfunctions, only the first nested function in a file may be called from the outside. Inside a function the rules are more complicated. In general a nested function may call:
As a complex example consider a parent function ex_top with two
child functions, ex_a and ex_b. In addition, ex_a has two
more child functions, ex_aa and ex_ab. For example:
function ex_top ()
## Can call: ex_top, ex_a, and ex_b
## Can NOT call: ex_aa and ex_ab
function ex_a ()
## Call call everything
function ex_aa ()
## Can call everything
endfunction
function ex_ab ()
## Can call everything
endfunction
endfunction
function ex_b ()
## Can call: ex_top, ex_a, and ex_b
## Can NOT call: ex_aa and ex_ab
endfunction
endfunction
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Functions can be overloaded to work with different input arguments. For
example, the operator ’+’ has been overloaded in Octave to work with single,
double, uint8, int32, and many other arguments. The preferred way to overload
functions is through classes and object oriented programming
(see section Function Overloading). Occasionally, however, one needs to undo
user overloading and call the default function associated with a specific
type. The builtin function exists for this purpose.
Call the base function f even if f is overloaded to another function for the given type signature.
This is normally useful when doing object-oriented programming and there is a requirement to call one of Octave’s base functions rather than the overloaded one of a new class.
A trivial example which redefines the sin function to be the
cos function shows how builtin works.
sin (0)
⇒ 0
function y = sin (x), y = cos (x); endfunction
sin (0)
⇒ 1
builtin ("sin", 0)
⇒ 0
|
A single dynamically linked file might define several functions. However, as Octave searches for functions based on the functions filename, Octave needs a manner in which to find each of the functions in the dynamically linked file. On operating systems that support symbolic links, it is possible to create a symbolic link to the original file for each of the functions which it contains.
However, there is at least one well known operating system that doesn’t
support symbolic links. Making copies of the original file for each of
the functions is undesirable as it increases the
amount of disk space used by Octave. Instead Octave supplies the
autoload function, that permits the user to define in which
file a certain function will be found.
Define function to autoload from file.
The second argument, file, should be an absolute file name or a file name in the same directory as the function or script from which the autoload command was run. file should not depend on the Octave load path.
Normally, calls to autoload appear in PKG_ADD script files that
are evaluated when a directory is added to Octave’s load path. To
avoid having to hardcode directory names in file, if file
is in the same directory as the PKG_ADD script then
autoload ("foo", "bar.oct");
|
will load the function foo from the file bar.oct. The above
usage when bar.oct is not in the same directory, or usages such as
autoload ("foo", file_in_loadpath ("bar.oct"))
|
are strongly discouraged, as their behavior may be unpredictable.
With no arguments, return a structure containing the current autoload map.
If a third argument "remove" is given, the function is cleared and
not loaded anymore during the current Octave session.
See also: PKG_ADD.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
It is sometime desirable to lock a function into memory with the
mlock function. This is typically used for dynamically linked
functions in Oct-files or mex-files that contain some initialization,
and it is desirable that calling clear does not remove this
initialization.
As an example,
function my_function () mlock (); … |
prevents my_function from being removed from memory after it is
called, even if clear is called. It is possible to determine if
a function is locked into memory with the mislocked, and to unlock
a function with munlock, which the following illustrates.
my_function ();
mislocked ("my_function")
⇒ ans = 1
munlock ("my_function");
mislocked ("my_function")
⇒ ans = 0
|
A common use of mlock is to prevent persistent variables from
being removed from memory, as the following example shows:
function count_calls ()
mlock ();
persistent calls = 0;
printf ("'count_calls' has been called %d times\n",
++calls);
endfunction
count_calls ();
-| 'count_calls' has been called 1 times
clear count_calls
count_calls ();
-| 'count_calls' has been called 2 times
|
mlock might equally be used to prevent changes to a function from having
effect in Octave, though a similar effect can be had with the
ignore_function_time_stamp function.
Lock the current function into memory so that it can’t be cleared.
See also: munlock, mislocked, persistent.
Unlock the named function fcn. If no function is named then unlock the current function.
See also: mlock, mislocked, persistent.
Return true if the named function fcn is locked. If no function is named then return true if the current function is locked.
See also: mlock, munlock, persistent.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Given the numerous different ways that Octave can define a function, it is possible and even likely that multiple versions of a function, might be defined within a particular scope. The precedence of which function will be used within a particular scope is given by
numel, size,
etc.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A script file is a file containing (almost) any sequence of Octave commands. It is read and evaluated just as if you had typed each command at the Octave prompt, and provides a convenient way to perform a sequence of commands that do not logically belong inside a function.
Unlike a function file, a script file must not begin with the
keyword function. If it does, Octave will assume that it is a
function file, and that it defines a single function that should be
evaluated as soon as it is defined.
A script file also differs from a function file in that the variables named in a script file are not local variables, but are in the same scope as the other variables that are visible on the command line.
Even though a script file may not begin with the function
keyword, it is possible to define more than one function in a single
script file and load (but not execute) all of them at once. To do
this, the first token in the file (ignoring comments and other white
space) must be something other than function. If you have no
other statements to evaluate, you can use a statement that has no
effect, like this:
# Prevent Octave from thinking that this # is a function file: 1; # Define function one: function one () … |
To have Octave read and compile these functions into an internal form,
you need to make sure that the file is in Octave’s load path
(accessible through the path function), then simply type the
base name of the file that contains the commands. (Octave uses the
same rules to search for script files as it does to search for
function files.)
If the first token in a file (ignoring comments) is function,
Octave will compile the function and try to execute it, printing a
message warning about any non-whitespace characters that appear after
the function definition.
Note that Octave does not try to look up the definition of any identifier until it needs to evaluate it. This means that Octave will compile the following statements if they appear in a script file, or are typed at the command line,
# not a function file: 1; function foo () do_something (); endfunction function do_something () do_something_else (); endfunction |
even though the function do_something is not defined before it is
referenced in the function foo. This is not an error because
Octave does not need to resolve all symbols that are referenced by a
function until the function is actually evaluated.
Since Octave doesn’t look for definitions until they are needed, the following code will always print ‘bar = 3’ whether it is typed directly on the command line, read from a script file, or is part of a function body, even if there is a function or script file called ‘bar.m’ in Octave’s path.
eval ("bar = 3");
bar
|
Code like this appearing within a function body could fool Octave if
definitions were resolved as the function was being compiled. It would
be virtually impossible to make Octave clever enough to evaluate this
code in a consistent fashion. The parser would have to be able to
perform the call to eval at compile time, and that would be
impossible unless all the references in the string to be evaluated could
also be resolved, and requiring that would be too restrictive (the
string might come from user input, or depend on things that are not
known until the function is evaluated).
Although Octave normally executes commands from script files that have
the name ‘file.m’, you can use the function source to
execute commands from any file.
Parse and execute the contents of file.
This is equivalent to executing commands from a script file, but without requiring the file to be named ‘file.m’.
See also: run.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
It can be very convenient store a function in a variable so that it can be passed to a different function. For example, a function that performs numerical minimization needs access to the function that should be minimized.
| 11.11.1 Function Handles | ||
| 11.11.2 Anonymous Functions | ||
| 11.11.3 Inline Functions |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A function handle is a pointer to another function and is defined with the syntax
@function-name |
For example,
f = @sin; |
creates a function handle called f that refers to the
function sin.
Function handles are used to call other functions indirectly, or to pass
a function as an argument to another function like quad or
fsolve. For example:
f = @sin;
quad (f, 0, pi)
⇒ 2
|
You may use feval to call a function using function handle, or
simply write the name of the function handle followed by an argument
list. If there are no arguments, you must use an empty argument list
‘()’. For example:
f = @sin;
feval (f, pi/4)
⇒ 0.70711
f (pi/4)
⇒ 0.70711
|
Return true if x is a function handle.
Return a structure containing information about the function handle fcn_handle.
The structure s always contains these 3 fields:
The function name. For an anonymous function (no name) this will be the actual function definition.
Type of the function.
The function is anonymous.
The function is private.
The function overloads an existing function.
The function is a built-in or m-file function.
The function is a subfunction within an m-file.
The m-file that will be called to perform the function. This field is empty for anonymous and built-in functions.
In addition, some function types may return more information in additional fields.
Warning: functions is provided for debugging purposes only.
It’s behavior may change in the future and programs should not depend on a
particular output.
Return a string containing the name of the function referenced by the function handle fcn_handle.
Return a function handle constructed from the string fcn_name.
If the optional "global" argument is passed, locally visible
functions are ignored in the lookup.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Anonymous functions are defined using the syntax
@(argument-list) expression |
Any variables that are not found in the argument list are inherited from
the enclosing scope. Anonymous functions are useful for creating simple
unnamed functions from expressions or for wrapping calls to other
functions to adapt them for use by functions like quad. For
example,
f = @(x) x.^2;
quad (f, 0, 10)
⇒ 333.33
|
creates a simple unnamed function from the expression x.^2 and
passes it to quad,
quad (@(x) sin (x), 0, pi)
⇒ 2
|
wraps another function, and
a = 1;
b = 2;
quad (@(x) betainc (x, a, b), 0, 0.4)
⇒ 0.13867
|
adapts a function with several parameters to the form required by
quad. In this example, the values of a and b that
are passed to betainc are inherited from the current
environment.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
An inline function is created from a string containing the function
body using the inline function. The following code defines the
function f(x) = x^2 + 2.
f = inline ("x^2 + 2");
|
After this it is possible to evaluate f at any x by
writing f(x).
Create an inline function from the character string str.
If called with a single argument, the arguments of the generated
function are extracted from the function itself. The generated
function arguments will then be in alphabetical order. It should
be noted that i, and j are ignored as arguments due to the
ambiguity between their use as a variable or their use as an inbuilt
constant. All arguments followed by a parenthesis are considered
to be functions. If no arguments are found, a function taking a single
argument named x will be created.
If the second and subsequent arguments are character strings, they are the names of the arguments of the function.
If the second argument is an integer n, the arguments are
"x", "P1", …, "PN".
Programming Note: The use of inline is discouraged and it may be
removed from a future version of Octave. The preferred way to create
functions from strings is through the use of anonymous functions
(see section Anonymous Functions) or str2func.
Return a cell array of character strings containing the names of the arguments of the inline function fun.
Return a character string representing the inline function fun.
Note that char (fun) is equivalent to
formula (fun).
Identify the argument names in the function defined by a string.
Common constant names such as pi, NaN, Inf,
eps, i or j are ignored. The arguments that are
found are returned in a cell array of strings. If no variables are
found then the returned cell array is empty.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Commands are a special class of functions that only accept string input arguments. A command can be called as an ordinary function, but it can also be called without the parentheses. For example,
my_command hello world |
is equivalent to
my_command ("hello", "world")
|
The general form of a command call is
cmdname arg1 arg2 … |
which translates directly to
cmdname ("arg1", "arg2", …)
|
Any regular function can be used as a command if it accepts string input arguments. For example:
toupper lower_case_arg ⇒ ans = LOWER_CASE_ARG |
One difficulty of commands occurs when one of the string input arguments is stored in a variable. Because Octave can’t tell the difference between a variable name and an ordinary string, it is not possible to pass a variable as input to a command. In such a situation a command must be called as a function. For example:
strvar = "hello world"; toupper strvar ⇒ ans = STRVAR toupper (strvar) ⇒ ans = HELLO WORLD |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Many of Octave’s standard functions are distributed as function files. They are loosely organized by topic, in subdirectories of ‘octave-home/lib/octave/version/m’, to make it easier to find them.
The following is a list of all the function file subdirectories, and the types of functions you will find there.
Functions for playing and recording sounds.
Out-of-date functions which will eventually be removed from Octave.
Elementary functions, principally trigonometric.
Class functions for the FTP object.
Miscellaneous matrix manipulations, like flipud, rot90,
and triu, as well as other basic functions, like
ismatrix, nargchk, etc.
Functions related to Delaunay triangulation.
Functions for Octave’s built-in help system.
Image processing tools. These functions require the X Window System.
Input-output functions.
Functions for linear algebra.
Functions that don’t really belong anywhere else.
Functions related to minimization, optimization, and root finding.
Functions to manage the directory path Octave uses to find functions.
Package manager for installing external packages of functions in Octave.
Functions for displaying and printing two- and three-dimensional graphs.
Functions for manipulating polynomials.
Functions implementing user-defined preferences.
Functions for creating and manipulating sets of unique values.
Functions for signal processing applications.
Functions for handling sparse matrices.
Special functions such as bessel or factor.
Functions that create special matrix forms such as Hilbert or Vandermonde matrices.
Octave’s system-wide startup file.
Statistical functions.
Miscellaneous string-handling functions.
Functions for performing unit tests on other functions.
Functions related to time and date processing.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave includes several functions for printing error and warning messages. When you write functions that need to take special action when they encounter abnormal conditions, you should print the error messages using the functions described in this chapter.
Since many of Octave’s functions use these functions, it is also useful to understand them, so that errors and warnings can be handled.
| 12.1 Handling Errors | ||
| 12.2 Handling Warnings |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
An error is something that occurs when a program is in a state where it doesn’t make sense to continue. An example is when a function is called with too few input arguments. In this situation the function should abort with an error message informing the user of the lacking input arguments.
Since an error can occur during the evaluation of a program, it is
very convenient to be able to detect that an error occurred, so that
the error can be fixed. This is possible with the try statement
described in The try Statement.
| 12.1.1 Raising Errors | ||
| 12.1.2 Catching Errors | ||
| 12.1.3 Recovering From Errors |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The most common use of errors is for checking input arguments to
functions. The following example calls the error function if
the function f is called without any input arguments.
function f (arg1)
if (nargin == 0)
error ("not enough input arguments");
endif
endfunction
|
When the error function is called, it prints the given message
and returns to the Octave prompt. This means that no code following
a call to error will be executed.
Format the optional arguments under the control of the template string
template using the same rules as the printf family of
functions (see section Formatted Output) and print the resulting message
on the stderr stream. The message is prefixed by the character
string ‘error: ’.
Calling error also sets Octave’s internal error state such that
control will return to the top level without evaluating any more
commands. This is useful for aborting from functions or scripts.
If the error message does not end with a new line character, Octave will print a traceback of all the function calls leading to the error. For example, given the following function definitions:
function f () g (); end
function g () h (); end
function h () nargin == 1 || error ("nargin != 1"); end
|
calling the function f will result in a list of messages that
can help you to quickly locate the exact location of the error:
f () error: nargin != 1 error: called from: error: error at line -1, column -1 error: h at line 1, column 27 error: g at line 1, column 15 error: f at line 1, column 15 |
If the error message ends in a new line character, Octave will print the message but will not display any traceback messages as it returns control to the top level. For example, modifying the error message in the previous example to end in a new line causes Octave to only print a single message:
function h () nargin == 1 || error ("nargin != 1\n"); end
f ()
error: nargin != 1
|
A null string ("") input to error will be ignored and the code
will continue running as if the statement were a NOP. This is for
compatibility with MATLAB. It also makes it possible to write code such
as
err_msg = ""; if (CONDITION 1) err_msg = "CONDITION 1 found"; elseif (CONDITION2) err_msg = "CONDITION 2 found"; … endif error (err_msg); |
which will only stop execution if an error has been found.
Implementation Note: For compatibility with MATLAB, escape
sequences (e.g., "n" => newline) are processed in template
regardless of whether template has been defined within single quotes
as long as there are two or more input arguments.
Use a second backslash to stop interpolation of the escape sequence (e.g.,
"\\n") or use the regexptranslate function.
Since it is common to use errors when there is something wrong with
the input to a function, Octave supports functions to simplify such code.
When the print_usage function is called, it reads the help text
of the function calling print_usage, and presents a useful error.
If the help text is written in Texinfo it is possible to present an
error message that only contains the function prototypes as described
by the @deftypefn parts of the help text. When the help text
isn’t written in Texinfo, the error message contains the entire help
message.
Consider the following function.
## -*- texinfo -*-
## @deftypefn {Function File} f (@var{arg1})
## Function help text goes here…
## @end deftypefn
function f (arg1)
if (nargin == 0)
print_usage ();
endif
endfunction
|
When it is called with no input arguments it produces the following error.
f () -| error: Invalid call to f. Correct usage is: -| -| -- Function File: f (ARG1) -| -| -| Additional help for built-in functions and operators is -| available in the online version of the manual. Use the command -| `doc <topic>' to search the manual index. -| -| Help and information about Octave is also available on the WWW -| at http://www.octave.org and via the help@octave.org -| mailing list. |
Print the usage message for a function. When called with no input arguments
the print_usage function displays the usage message of the currently
executing function.
See also: help.
Print the message msg, prefixed by the string ‘usage: ’, and set Octave’s internal error state such that control will return to the top level without evaluating any more commands. This is useful for aborting from functions.
After usage is evaluated, Octave will print a traceback of all
the function calls leading to the usage message.
You should use this function for reporting problems errors that result from an improper call to a function, such as calling a function with an incorrect number of arguments, or with arguments of the wrong type. For example, most functions distributed with Octave begin with code like this
if (nargin != 2)
usage ("foo (a, b)");
endif
|
to check for the proper number of arguments.
Produce a beep from the speaker (or visual bell).
Query or set the internal variable that controls whether Octave will try to ring the terminal bell before printing an error message.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
When an error occurs, it can be detected and handled using the
try statement as described in The try Statement.
As an example, the following piece of code counts the number of errors
that occurs during a for loop.
number_of_errors = 0;
for n = 1:100
try
…
catch
number_of_errors++;
end_try_catch
endfor
|
The above example treats all errors the same. In many situations it
can however be necessary to discriminate between errors, and take
different actions depending on the error. The lasterror
function returns a structure containing information about the last
error that occurred. As an example, the code above could be changed
to count the number of errors related to the ‘*’ operator.
number_of_errors = 0;
for n = 1:100
try
…
catch
msg = lasterror.message;
if (strfind (msg, "operator *"))
number_of_errors++;
endif
end_try_catch
endfor
|
Alternatively, the output of the lasterror function can be found
in a variable indicated immediately after the catch keyword, as
in the example below showing how to redirect an error as a warning:
try … catch err warning(err.identifier, err.message); … end_try_catch |
Query or set the last error message structure. When called without arguments, return a structure containing the last error message and other information related to this error. The elements of the structure are:
messageThe text of the last error message
identifierThe message identifier of this error message
stackA structure containing information on where the message occurred. This may be an empty structure if the information cannot be obtained. The fields of the structure are:
fileThe name of the file where the error occurred
nameThe name of function in which the error occurred
lineThe line number at which the error occurred
columnAn optional field with the column number at which the error occurred
The last error structure may be set by passing a scalar structure, err, as input. Any fields of err that match those above are set while any unspecified fields are initialized with default values.
If lasterror is called with the argument "reset", all
fields are set to their default values.
Query or set the last error message. When called without input arguments, return the last error message and message identifier. With one argument, set the last error message to msg. With two arguments, also set the last message identifier.
It is also possible to assign an identification string to an error.
If an error has such an ID the user can catch this error
as will be shown in the next example. To assign an ID to an error,
simply call error with two string arguments, where the first
is the identification string, and the second is the actual error. Note
that error IDs are in the format "NAMESPACE:ERROR-NAME". The namespace
"Octave" is used for Octave’s own errors. Any other string is available
as a namespace for user’s own errors.
The next example counts indexing errors. The errors are caught using the
field identifier of the structure returned by the function lasterror.
number_of_errors = 0;
for n = 1:100
try
…
catch
id = lasterror.identifier;
if (strcmp (id, "Octave:invalid-indexing"))
number_of_errors++;
endif
end_try_catch
endfor
|
The functions distributed with Octave can issue one of the following errors.
Octave:invalid-contextIndicates the error was generated by an operation that cannot be executed in
the scope from which it was called. For example, the function
print_usage () when called from the Octave prompt raises this error.
Octave:invalid-input-argIndicates that a function was called with invalid input arguments.
Octave:invalid-fun-callIndicates that a function was called in an incorrect way, e.g., wrong number of input arguments.
Octave:invalid-indexingIndicates that a data-type was indexed incorrectly, e.g., real-value index for arrays, non-existent field of a structure.
Octave:bad-allocIndicates that memory couldn’t be allocated.
Octave:undefined-functionIndicates a call to a function that is not defined. The function may exist but Octave is unable to find it in the search path.
When an error has been handled it is possible to raise it again. This
can be useful when an error needs to be detected, but the program should
still abort. This is possible using the rethrow function. The
previous example can now be changed to count the number of errors
related to the ‘*’ operator, but still abort if another kind of
error occurs.
number_of_errors = 0;
for n = 1:100
try
…
catch
msg = lasterror.message;
if (strfind (msg, "operator *"))
number_of_errors++;
else
rethrow (lasterror);
endif
end_try_catch
endfor
|
Reissue a previous error as defined by err. err is a structure
that must contain at least the "message" and "identifier"
fields. err can also contain a field "stack" that gives
information on the assumed location of the error. Typically err is
returned from lasterror.
Return the current value of the system-dependent variable errno, set its value to val and return the previous value, or return the named error code given name as a character string, or -1 if name is not found.
Return a structure containing the system-dependent errno values.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave provides several ways of recovering from errors. There are
try/catch blocks,
unwind_protect/unwind_protect_cleanup blocks,
and finally the onCleanup command.
The onCleanup command associates an ordinary Octave variable (the
trigger) with an arbitrary function (the action). Whenever the Octave variable
ceases to exist—whether due to a function return, an error, or simply because
the variable has been removed with clear—then the assigned function
is executed.
The function can do anything necessary for cleanup such as closing open file handles, printing an error message, or restoring global variables to their initial values. The last example is a very convenient idiom for Octave code. For example:
function rand42
old_state = rand ("state");
restore_state = onCleanup (@() rand ("state", old_state);
rand ("state", 42);
…
endfunction # rand generator state restored by onCleanup
|
Create a special object that executes a given function upon destruction. If the object is copied to multiple variables (or cell or struct array elements) or returned from a function, function will be executed after clearing the last copy of the object. Note that if multiple local onCleanup variables are created, the order in which they are called is unspecified. For similar functionality See section The unwind_protect Statement.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Like an error, a warning is issued when something unexpected happens.
Unlike an error, a warning doesn’t abort the currently running program.
A simple example of a warning is when a number is divided by zero. In
this case Octave will issue a warning and assign the value Inf
to the result.
a = 1/0
-| warning: division by zero
⇒ a = Inf
|
| 12.2.1 Issuing Warnings | ||
| 12.2.2 Enabling and Disabling Warnings |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
It is possible to issue warnings from any code using the warning
function. In its most simple form, the warning function takes a
string describing the warning as its input argument. As an example,
the following code controls if the variable ‘a’ is non-negative,
and if not issues a warning and sets ‘a’ to zero.
a = -1;
if (a < 0)
warning ("'a' must be non-negative. Setting 'a' to zero.");
a = 0;
endif
-| 'a' must be non-negative. Setting 'a' to zero.
|
Since warnings aren’t fatal to a running program, it is not possible
to catch a warning using the try statement or something similar.
It is however possible to access the last warning as a string using the
lastwarn function.
It is also possible to assign an identification string to a warning.
If a warning has such an ID the user can enable and disable this warning
as will be described in the next section. To assign an ID to a warning,
simply call warning with two string arguments, where the first
is the identification string, and the second is the actual warning. Note
that warning IDs are in the format "NAMESPACE:WARNING-NAME". The
namespace "Octave" is used for Octave’s own warnings. Any other string
is available as a namespace for user’s own warnings.
Format the optional arguments under the control of the template string
template using the same rules as the printf family of
functions (see section Formatted Output) and print the resulting message
on the stderr stream. The message is prefixed by the character
string ‘warning: ’.
You should use this function when you want to notify the user
of an unusual condition, but only when it makes sense for your program
to go on.
The optional message identifier allows users to enable or disable
warnings tagged by id. A message identifier is of the form
"NAMESPACE:WARNING-NAME". Octave’s own warnings use the "Octave"
namespace (see XREFwarning_ids). The special identifier "all"
may be used to set the state of all warnings.
If the first argument is "on" or "off",
set the state of a particular warning using the identifier id. If the
first argument is "query", query the state of this warning
instead. If the identifier is omitted, a value of "all" is
assumed. If you set the state of a warning to "error", the
warning named by id is handled as if it were an error instead. So,
for example, the following handles all warnings as errors:
warning ("error");
|
If the state is "on", "off", or "error"
and the third argument is "local", then the warning state
will be set temporarily, until the end of the current function.
Changes to warning states that are set locally affect the current
function and all functions called from the current scope. The
previous warning state is restored on return from the current
function. The "local" option is ignored if used in the top-level
workspace.
Implementation Note: For compatibility with MATLAB, escape
sequences (e.g., "n" => newline) are processed in template
regardless of whether template has been defined within single quotes
as long as there are two or more input arguments.
Use a second backslash to stop interpolation of the escape sequence (e.g.,
"\\n") or use the regexptranslate function.
See also: warning_ids, lastwarn, error.
Query or set the last warning message. When called without input arguments, return the last warning message and message identifier. With one argument, set the last warning message to msg. With two arguments, also set the last message identifier.
The functions distributed with Octave can issue one of the following warnings.
Octave:abbreviated-property-matchBy default, the Octave:abbreviated-property-match warning is enabled.
Octave:array-to-scalarIf the Octave:array-to-scalar warning is enabled, Octave will
warn when an implicit conversion from an array to a scalar value is
attempted.
By default, the Octave:array-to-scalar warning is disabled.
Octave:array-to-vectorIf the Octave:array-to-vector warning is enabled, Octave will
warn when an implicit conversion from an array to a vector value is
attempted.
By default, the Octave:array-to-vector warning is disabled.
Octave:assign-as-truth-valueIf the Octave:assign-as-truth-value warning is
enabled, a warning is issued for statements like
if (s = t) … |
since such statements are not common, and it is likely that the intent was to write
if (s == t) … |
instead.
There are times when it is useful to write code that contains
assignments within the condition of a while or if
statement. For example, statements like
while (c = getc ()) … |
are common in C programming.
It is possible to avoid all warnings about such statements by
disabling the Octave:assign-as-truth-value warning,
but that may also let real errors like
if (x = 1) # intended to test (x == 1)! … |
slip by.
In such cases, it is possible suppress errors for specific statements by writing them with an extra set of parentheses. For example, writing the previous example as
while ((c = getc ())) … |
will prevent the warning from being printed for this statement, while allowing Octave to warn about other assignments used in conditional contexts.
By default, the Octave:assign-as-truth-value warning is enabled.
Octave:associativity-changeIf the Octave:associativity-change warning is
enabled, Octave will warn about possible changes in the meaning of
some code due to changes in associativity for some operators.
Associativity changes have typically been made for MATLAB
compatibility.
By default, the Octave:associativity-change warning is enabled.
Octave:autoload-relative-file-nameIf the Octave:autoload-relative-file-name is enabled,
Octave will warn when parsing autoload() function calls with relative
paths to function files. This usually happens when using autoload()
calls in PKG_ADD files, when the PKG_ADD file is not in the same
directory as the .oct file referred to by the autoload() command.
By default, the Octave:autoload-relative-file-name warning is enabled.
Octave:broadcastWarn when performing broadcasting operations. By default, this is enabled. See Broadcasting in the chapter Vectorization and Faster Code Execution of the manual.
Octave:built-in-variable-assignmentBy default, the Octave:built-in-variable-assignment warning is
enabled.
Octave:deprecated-keywordIf the Octave:deprecated-keyword warning is enabled, a
warning is issued when Octave encounters a keyword that is obsolete and
scheduled for removal from Octave.
By default, the Octave:deprecated-keyword warning is enabled.
Octave:divide-by-zeroIf the Octave:divide-by-zero warning is enabled, a
warning is issued when Octave encounters a division by zero.
By default, the Octave:divide-by-zero warning is enabled.
Octave:fopen-file-in-pathBy default, the Octave:fopen-file-in-path warning is enabled.
Octave:function-name-clashIf the Octave:function-name-clash warning is enabled, a
warning is issued when Octave finds that the name of a function
defined in a function file differs from the name of the file. (If
the names disagree, the name declared inside the file is ignored.)
By default, the Octave:function-name-clash warning is enabled.
Octave:future-time-stampIf the Octave:future-time-stamp warning is enabled, Octave
will print a warning if it finds a function file with a time stamp
that is in the future.
By default, the Octave:future-time-stamp warning is enabled.
Octave:glyph-renderBy default, the Octave:glyph-render warning is enabled.
Octave:imag-to-realIf the Octave:imag-to-real warning is enabled, a warning is
printed for implicit conversions of complex numbers to real numbers.
By default, the Octave:imag-to-real warning is disabled.
Octave:load-file-in-pathBy default, the Octave:load-file-in-path warning is enabled.
Octave:logical-conversionBy default, the Octave:logical-conversion warning is enabled.
Octave:matlab-incompatiblePrint warnings for Octave language features that may cause
compatibility problems with MATLAB.
By default, the Octave:matlab-incompatible warning is disabled.
The –traditional or –braindead startup options for Octave may also
be of use, see section Command Line Options.
Octave:md5sum-file-in-pathBy default, the Octave:md5sum-file-in-path warning is enabled.
Octave:missing-glyphBy default, the Octave:missing-glyph warning is enabled.
Octave:missing-semicolonIf the Octave:missing-semicolon warning is enabled, Octave
will warn when statements in function definitions don’t end in
semicolons.
By default the Octave:missing-semicolon warning is disabled.
Octave:mixed-string-concatIf the Octave:mixed-string-concat warning is enabled, print a
warning when concatenating a mixture of double and single quoted strings.
By default, the Octave:mixed-string-concat warning is disabled.
Octave:neg-dim-as-zeroIf the Octave:neg-dim-as-zero warning is enabled, print a warning
for expressions like
eye (-1) |
By default, the Octave:neg-dim-as-zero warning is disabled.
Octave:nested-functions-coercedBy default, the Octave:nested-functions-coerced warning is enabled.
Octave:noninteger-range-as-indexBy default, the Octave:noninteger-range-as-index warning is enabled.
Octave:num-to-strIf the Octave:num-to-str warning is enable, a warning is
printed for implicit conversions of numbers to their ASCII character
equivalents when strings are constructed using a mixture of strings and
numbers in matrix notation. For example,
[ "f", 111, 111 ] ⇒ "foo" |
elicits a warning if the Octave:num-to-str warning is
enabled. By default, the Octave:num-to-str warning is enabled.
Octave:possible-matlab-short-circuit-operatorIf the Octave:possible-matlab-short-circuit-operator warning
is enabled, Octave will warn about using the not short circuiting
operators & and | inside if or while
conditions. They normally never short circuit, but MATLAB always
short circuits if any logical operators are used in a condition. You
can turn on the option
do_braindead_shortcircuit_evaluation (1) |
if you would like to enable this short-circuit evaluation in
Octave. Note that the && and || operators always short
circuit in both Octave and MATLAB, so it’s only necessary to
enable MATLAB-style short-circuiting if it’s too arduous to modify
existing code that relies on this behavior.
By default, the Octave:possible-matlab-short-circuit-operator warning
is enabled.
Octave:precedence-changeIf the Octave:precedence-change warning is enabled, Octave
will warn about possible changes in the meaning of some code due to
changes in precedence for some operators. Precedence changes have
typically been made for MATLAB compatibility.
By default, the Octave:precedence-change warning is enabled.
Octave:recursive-path-searchBy default, the Octave:recursive-path-search warning is enabled.
Octave:remove-init-dirThe path function changes the search path that Octave uses
to find functions. It is possible to set the path to a value which
excludes Octave’s own built-in functions. If the
Octave:remove-init-dir warning is enabled then Octave will warn
when the path function has been used in a way that may render
Octave unworkable.
By default, the Octave:remove-init-dir warning is enabled.
Octave:reload-forces-clearIf several functions have been loaded from the same file, Octave must
clear all the functions before any one of them can be reloaded. If
the Octave:reload-forces-clear warning is enabled, Octave will
warn you when this happens, and print a list of the additional
functions that it is forced to clear.
By default, the Octave:reload-forces-clear warning is enabled.
Octave:resize-on-range-errorIf the Octave:resize-on-range-error warning is enabled, print a
warning when a matrix is resized by an indexed assignment with
indices outside the current bounds.
By default, the ## Octave:resize-on-range-error warning is disabled.
Octave:separator-insertPrint warning if commas or semicolons might be inserted
automatically in literal matrices.
By default, the Octave:separator-insert warning is disabled.
Octave:shadowed-functionBy default, the Octave:shadowed-function warning is enabled.
Octave:single-quote-stringPrint warning if a single quote character is used to introduce a
string constant.
By default, the Octave:single-quote-string warning is disabled.
Octave:singular-matrix-divBy default, the Octave:singular-matrix-div warning is enabled.
Octave:sqrtm:SingularMatrixBy default, the Octave:sqrtm:SingularMatrix warning is enabled.
Octave:str-to-numIf the Octave:str-to-num warning is enabled, a warning is printed
for implicit conversions of strings to their numeric ASCII equivalents.
For example,
"abc" + 0 ⇒ 97 98 99 |
elicits a warning if the Octave:str-to-num warning is enabled.
By default, the Octave:str-to-num warning is disabled.
Octave:undefined-return-valuesIf the Octave:undefined-return-values warning is disabled,
print a warning if a function does not define all the values in
the return list which are expected.
By default, the Octave:undefined-return-values warning is enabled.
Octave:variable-switch-labelIf the Octave:variable-switch-label warning is enabled, Octave
will print a warning if a switch label is not a constant or constant
expression.
By default, the Octave:variable-switch-label warning is disabled.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The warning function also allows you to control which warnings
are actually printed to the screen. If the warning function
is called with a string argument that is either "on" or "off"
all warnings will be enabled or disabled.
It is also possible to enable and disable individual warnings through their string identifications. The following code will issue a warning
warning ("example:non-negative-variable",
"'a' must be non-negative. Setting 'a' to zero.");
|
while the following won’t issue a warning
warning ("off", "example:non-negative-variable");
warning ("example:non-negative-variable",
"'a' must be non-negative. Setting 'a' to zero.");
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave includes a built-in debugger to aid in the development of scripts. This can be used to interrupt the execution of an Octave script at a certain point, or when certain conditions are met. Once execution has stopped, and debug mode is entered, the symbol table at the point where execution has stopped can be examined and modified to check for errors.
The normal command-line editing and history functions are available in debug mode.
| 13.1 Entering Debug Mode | ||
| 13.2 Leaving Debug Mode | ||
| 13.3 Breakpoints | ||
| 13.4 Debug Mode | ||
| 13.5 Call Stack | ||
| 13.6 Profiling | ||
| 13.7 Profiler Example |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There are two basic means of interrupting the execution of an Octave script. These are breakpoints (see section Breakpoints), discussed in the next section, and interruption based on some condition.
Octave supports three means to stop execution based on the values set in
the functions debug_on_interrupt, debug_on_warning, and
debug_on_error.
Query or set the internal variable that controls whether Octave will try to enter debugging mode when it receives an interrupt signal (typically generated with C-c). If a second interrupt signal is received before reaching the debugging mode, a normal interrupt will occur.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: debug_on_error, debug_on_warning.
Query or set the internal variable that controls whether Octave will try to enter the debugger when a warning is encountered.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: debug_on_error, debug_on_interrupt.
Query or set the internal variable that controls whether Octave will try to enter the debugger when an error is encountered. This will also inhibit printing of the normal traceback message (you will only see the top-level error message).
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: debug_on_warning, debug_on_interrupt.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Use either dbcont or return to leave the debug mode and
continue the normal execution of the script.
Leave command-line debugging mode and continue code execution normally.
To quit debug mode and return directly to the prompt without executing
any additional code use dbquit.
Quit debugging mode immediately without further code execution and return to the Octave prompt.
Finally, typing exit or quit at the debug prompt will
result in Octave terminating normally.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Breakpoints can be set in any m-file function by using the dbstop
function.
Set a breakpoint in function func.
Arguments are
Function name as a string variable. When already in debug mode this should be left out and only the line should be given.
Line number where the breakpoint should be set. Multiple lines may be given as separate arguments or as a vector.
When called with a single argument func, the breakpoint is set at the first executable line in the named function.
The optional output rline is the real line number where the breakpoint was set. This can differ from specified line if the line is not executable. For example, if a breakpoint attempted on a blank line then Octave will set the real breakpoint at the next executable line.
See also: dbclear, dbstatus, dbstep, debug_on_error, debug_on_warning, debug_on_interrupt.
Breakpoints in class methods are also supported (e.g.,
dbstop ("@class/method")). However, breakpoints cannot be set in
built-in functions (e.g., sin, etc.) or dynamically loaded functions
(i.e., oct-files).
To set a breakpoint immediately upon entering a function use line number 1, or omit the line number entirely and just give the function name. When setting the breakpoint Octave will ignore the leading comment block, and the breakpoint will be set on the first executable statement in the function. For example:
dbstop ("asind", 1)
⇒ 29
|
Note that the return value of 29 means that the breakpoint was
effectively set to line 29. The status of breakpoints in a function can
be queried with dbstatus.
Report the location of active breakpoints.
When called with no input or output arguments, print the list of all functions with breakpoints and the line numbers where those breakpoints are set. If a function name func is specified then only report breakpoints for the named function.
The optional return argument brk_list is a struct array with the following fields.
The name of the function with a breakpoint.
The name of the m-file where the function code is located.
A line number, or vector of line numbers, with a breakpoint.
Reusing the previous example, dbstatus ("asind") will return
29. The breakpoints listed can then be cleared with the dbclear
function.
Delete a breakpoint in the function func.
Arguments are
Function name as a string variable. When already in debug mode this argument should be omitted and only the line number should be given.
Line number from which to remove a breakpoint. Multiple lines may be given as separate arguments or as a vector.
When called without a line number specification all breakpoints in the named function are cleared.
If the requested line is not a breakpoint no action is performed.
A breakpoint may also be set in a subfunction. For example, if a file contains the functions
function y = func1 (x) y = func2 (x); endfunction function y = func2 (x) y = x + 1; endfunction |
then a breakpoint can be set at the start of the subfunction directly with
dbstop (["func1", filemarker(), "func2"]) ⇒ 5 |
Note that filemarker returns the character that marks subfunctions from
the file containing them. Unless the default has been changed this character
is ‘>’. Thus, a quicker and more normal way to set the breakpoint would
be
dbstop func1>func2 |
Another simple way of setting a breakpoint in an Octave script is the
use of the keyboard function.
This function is normally used for simple debugging. When the
keyboard function is executed, Octave prints a prompt and waits
for user input. The input strings are then evaluated and the results
are printed. This makes it possible to examine the values of variables
within a function, and to assign new values if necessary. To leave the
prompt and return to normal execution type ‘return’ or ‘dbcont’.
The keyboard function does not return an exit status.
If keyboard is invoked without arguments, a default prompt of
‘debug> ’ is used.
The keyboard function is placed in a script at the point where the user
desires that the execution be stopped. It automatically sets the running
script into the debug mode.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There are three additional support functions that allow the user to find out where in the execution of a script Octave entered the debug mode, and to print the code in the script surrounding the point where Octave entered debug mode.
In debugging mode, report the current file and line number where execution is stopped.
Display a script file with line numbers.
When called with no arguments in debugging mode, display the script file
currently being debugged. An optional range specification can be used to
list only a portion of the file. The special keyword "end" is a
valid line number specification for the last line of the file.
When called with the name of a function, list that script file with line numbers.
In debugging mode, list n lines of the function being debugged centered around the current line to be executed. If unspecified n defaults to 10 (+/- 5 lines)
You may also use isdebugmode to determine whether the debugger is
currently active.
Return true if in debugging mode, otherwise false.
Debug mode also allows single line stepping through a function using
the command dbstep.
In debugging mode, execute the next n lines of code. If n is omitted, execute the next single line of code. If the next line of code is itself defined in terms of an m-file remain in the existing function.
Using dbstep in will cause execution of the next line to step into
any m-files defined on the next line. Using dbstep out will cause
execution to continue until the current function returns.
dbnext is an alias for dbstep.
When in debug mode the <RETURN> key will execute the last entered command.
This is useful, for example, after hitting a breakpoint and entering
dbstep once. After that, one can advance line by line through the code
with only a single key stroke.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The function being debugged may be the leaf node of a series of function calls.
After examining values in the current subroutine it may turn out that the
problem occurred in earlier pieces of code. Use dbup and dbdown
to move up and down through the series of function calls to locate where
variables first took on the wrong values. dbstack shows the entire
series of function calls and at what level debugging is currently taking place.
Display or return current debugging function stack information. With optional argument n, omit the n innermost stack frames.
Although accepted, the argument -completenames is silently ignored. Octave always returns absolute file names. The arguments n and -completenames can be both specified in any order.
The optional return argument stack is a struct array with the following fields:
The name of the m-file where the function code is located.
The name of the function with a breakpoint.
The line number of an active breakpoint.
The column number of the line where the breakpoint begins.
Undocumented.
Undocumented.
The return argument idx specifies which element of the stack struct array is currently active.
In debugging mode, move up the execution stack n frames. If n is omitted, move up one frame.
In debugging mode, move down the execution stack n frames. If n is omitted, move down one frame.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave supports profiling of code execution on a per-function level. If profiling is enabled, each call to a function (supporting built-ins, operators, functions in oct- and mex-files, user-defined functions in Octave code and anonymous functions) is recorded while running Octave code. After that, this data can aid in analyzing the code behavior, and is in particular helpful for finding “hot spots” in the code which use up a lot of computation time and are the best targets to spend optimization efforts on.
The main command for profiling is profile, which can be used to
start or stop the profiler and also to query collected data afterwards.
The data is returned in an Octave data structure which can then be
examined or further processed by other routines or tools.
Control the built-in profiler.
profile onStart the profiler, clearing all previously collected data if there is any.
profile offStop profiling. The collected data can later be retrieved and examined
with calls like S = profile ("info").
profile clearClear all collected profiler data.
profile resumeRestart profiling without cleaning up the old data and instead all newly collected statistics are added to the already existing ones.
S = profile ("status")Return a structure filled with certain information about the current status
of the profiler. At the moment, the only field is ProfilerStatus
which is either "on" or "off".
T = profile ("info")Return the collected profiling statistics in the structure T.
The flat profile is returned in the field FunctionTable which is an
array of structures, each entry corresponding to a function which was called
and for which profiling statistics are present. Furthermore, the field
Hierarchical contains the hierarchical call-tree. Each node
has an index into the FunctionTable identifying the function it
corresponds to as well as data fields for number of calls and time spent
at this level in the call-tree.
See also: profshow, profexplore.
An easy way to get an overview over the collected data is
profshow. This function takes the profiler data returned by
profile as input and prints a flat profile, for instance:
Function Attr Time (s) Calls ---------------------------------------- >myfib R 2.195 13529 binary <= 0.061 13529 binary - 0.050 13528 binary + 0.026 6764 |
This shows that most of the run time was spent executing the function ‘myfib’, and some minor proportion evaluating the listed binary operators. Furthermore, it is shown how often the function was called and the profiler also records that it is recursive.
Show flat profiler results.
This command prints out profiler data as a flat profile. data is the
structure returned by profile ("info"). If n is given, it
specifies the number of functions to show in the profile; functions are
sorted in descending order by total time spent in them. If there are more
than n included in the profile, those will not be shown. n
defaults to 20.
The attribute column shows ‘R’ for recursive functions and nothing otherwise.
See also: profexplore, profile.
Interactively explore hierarchical profiler output.
Assuming data is the structure with profile data returned by
profile (, this command opens an interactive prompt
that can be used to explore the call-tree. Type help to get a list
of possible commands. If data is omitted, "info")profile ("info")
is called and used in its place.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Below, we will give a short example of a profiler session. See section Profiling, for the documentation of the profiler functions in detail. Consider the code:
global N A;
N = 300;
A = rand (N, N);
function xt = timesteps (steps, x0, expM)
global N;
if (steps == 0)
xt = NA (N, 0);
else
xt = NA (N, steps);
x1 = expM * x0;
xt(:, 1) = x1;
xt(:, 2 : end) = timesteps (steps - 1, x1, expM);
endif
endfunction
function foo ()
global N A;
initial = @(x) sin (x);
x0 = (initial (linspace (0, 2 * pi, N)))';
expA = expm (A);
xt = timesteps (100, x0, expA);
endfunction
function fib = bar (N)
if (N <= 2)
fib = 1;
else
fib = bar (N - 1) + bar (N - 2);
endif
endfunction
|
If we execute the two main functions, we get:
tic; foo; toc; ⇒ Elapsed time is 2.37338 seconds. tic; bar (20); toc; ⇒ Elapsed time is 2.04952 seconds. |
But this does not give much information about where this time is spent;
for instance, whether the single call to expm is more expensive
or the recursive time-stepping itself. To get a more detailed picture,
we can use the profiler.
profile on;
foo;
profile off;
data = profile ("info");
profshow (data, 10);
|
This prints a table like:
# Function Attr Time (s) Calls --------------------------------------------- 7 expm 1.034 1 3 binary * 0.823 117 41 binary \ 0.188 1 38 binary ^ 0.126 2 43 timesteps R 0.111 101 44 NA 0.029 101 39 binary + 0.024 8 34 norm 0.011 1 40 binary - 0.004 101 33 balance 0.003 1 |
The entries are the individual functions which have been executed (only
the 10 most important ones), together with some information for each of
them. The entries like ‘binary *’ denote operators, while other
entries are ordinary functions. They include both built-ins like
expm and our own routines (for instance timesteps). From
this profile, we can immediately deduce that expm uses up the
largest proportion of the processing time, even though it is only called
once. The second expensive operation is the matrix-vector product in the
routine timesteps. (6)
Timing, however, is not the only information available from the profile.
The attribute column shows us that timesteps calls itself
recursively. This may not be that remarkable in this example (since it’s
clear anyway), but could be helpful in a more complex setting. As to the
question of why is there a ‘binary \’ in the output, we can easily
shed some light on that too. Note that data is a structure array
(Structure Arrays) which contains the field FunctionTable.
This stores the raw data for the profile shown. The number in the first
column of the table gives the index under which the shown function can
be found there. Looking up data.FunctionTable(41) gives:
scalar structure containing the fields:
FunctionName = binary \
TotalTime = 0.18765
NumCalls = 1
IsRecursive = 0
Parents = 7
Children = [](1x0)
|
Here we see the information from the table again, but have additional
fields Parents and Children. Those are both arrays, which
contain the indices of functions which have directly called the function
in question (which is entry 7, expm, in this case) or been called
by it (no functions). Hence, the backslash operator has been used
internally by expm.
Now let’s take a look at bar. For this, we start a fresh
profiling session (profile on does this; the old data is removed
before the profiler is restarted):
profile on;
bar (20);
profile off;
profshow (profile ("info"));
|
This gives:
# Function Attr Time (s) Calls ------------------------------------------------------- 1 bar R 2.091 13529 2 binary <= 0.062 13529 3 binary - 0.042 13528 4 binary + 0.023 6764 5 profile 0.000 1 8 false 0.000 1 6 nargin 0.000 1 7 binary != 0.000 1 9 __profiler_enable__ 0.000 1 |
Unsurprisingly, bar is also recursive. It has been called 13,529
times in the course of recursively calculating the Fibonacci number in a
suboptimal way, and most of the time was spent in bar itself.
Finally, let’s say we want to profile the execution of both foo
and bar together. Since we already have the run-time data
collected for bar, we can restart the profiler without clearing
the existing data and collect the missing statistics about foo.
This is done by:
profile resume;
foo;
profile off;
profshow (profile ("info"), 10);
|
As you can see in the table below, now we have both profiles mixed together.
# Function Attr Time (s) Calls --------------------------------------------- 1 bar R 2.091 13529 16 expm 1.122 1 12 binary * 0.798 117 46 binary \ 0.185 1 45 binary ^ 0.124 2 48 timesteps R 0.115 101 2 binary <= 0.062 13529 3 binary - 0.045 13629 4 binary + 0.041 6772 49 NA 0.036 101 |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave supports several ways of reading and writing data to or from the prompt or a file. The simplest functions for data Input and Output (I/O) are easy to use, but only provide limited control of how data is processed. For more control, a set of functions modeled after the C standard library are also provided by Octave.
| 14.1 Basic Input and Output | ||
| 14.2 C-Style I/O Functions |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 14.1.1 Terminal Output | ||
| 14.1.2 Terminal Input | ||
| 14.1.3 Simple File I/O |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Since Octave normally prints the value of an expression as soon as it has been evaluated, the simplest of all I/O functions is a simple expression. For example, the following expression will display the value of ‘pi’
pi
-| pi = 3.1416
|
This works well as long as it is acceptable to have the name of the
variable (or ‘ans’) printed along with the value. To print the
value of a variable without printing its name, use the function
disp.
The format command offers some control over the way Octave prints
values with disp and through the normal echoing mechanism.
Display the value of x. For example:
disp ("The value of pi is:"), disp (pi)
-| the value of pi is:
-| 3.1416
|
Note that the output from disp always ends with a newline.
If an output value is requested, disp prints nothing and
returns the formatted output in a string.
See also: fdisp.
Return a string containing the elements of arg listed in columns with an overall maximum width of width and optional prefix prefix. The argument arg must be a cell array of character strings or a character array. If width is not specified or is an empty matrix, or less than or equal to zero, the width of the terminal screen is used. Newline characters are used to break the lines in the output string. For example:
list_in_columns ({"abc", "def", "ghijkl", "mnop", "qrs", "tuv"}, 20)
⇒ abc mnop
def qrs
ghijkl tuv
whos ans
⇒
Variables in the current scope:
Attr Name Size Bytes Class
==== ==== ==== ===== =====
ans 1x37 37 char
Total is 37 elements using 37 bytes
|
See also: terminal_size.
Return a two-element row vector containing the current size of the terminal window in characters (rows and columns).
See also: list_in_columns.
Reset or specify the format of the output produced by disp and
Octave’s normal echoing mechanism. This command only affects the display
of numbers but not how they are stored or computed. To change the internal
representation from the default double use one of the conversion functions
such as single, uint8, int64, etc.
By default, Octave displays 5 significant digits in a human readable form
(option ‘short’ paired with ‘loose’ format for matrices).
If format is invoked without any options, this default format
is restored.
Valid formats for floating point numbers are listed in the following table.
shortFixed point format with 5 significant figures in a field that is a maximum of 10 characters wide. (default).
If Octave is unable to format a matrix so that columns line up on the decimal point and all numbers fit within the maximum field width then it switches to an exponential ‘e’ format.
longFixed point format with 15 significant figures in a field that is a maximum of 20 characters wide.
As with the ‘short’ format, Octave will switch to an exponential ‘e’ format if it is unable to format a matrix properly using the current format.
short elong eExponential format. The number to be represented is split between a mantissa
and an exponent (power of 10). The mantissa has 5 significant digits in the
short format and 15 digits in the long format.
For example, with the ‘short e’ format, pi is displayed as
3.1416e+00.
short Elong EIdentical to ‘short e’ or ‘long e’ but displays an uppercase
‘E’ to indicate the exponent.
For example, with the ‘long E’ format, pi is displayed as
3.14159265358979E+00.
short glong gOptimally choose between fixed point and exponential format based on
the magnitude of the number.
For example, with the ‘short g’ format,
pi .^ [2; 4; 8; 16; 32] is displayed as
ans =
9.8696
97.409
9488.5
9.0032e+07
8.1058e+15
|
short englong engIdentical to ‘short e’ or ‘long e’ but displays the value
using an engineering format, where the exponent is divisible by 3. For
example, with the ‘short eng’ format, 10 * pi is displayed as
31.4159e+00.
long Gshort GIdentical to ‘short g’ or ‘long g’ but displays an uppercase ‘E’ to indicate the exponent.
freenonePrint output in free format, without trying to line up columns of matrices on the decimal point. This also causes complex numbers to be formatted as numeric pairs like this ‘(0.60419, 0.60709)’ instead of like this ‘0.60419 + 0.60709i’.
The following formats affect all numeric output (floating point and integer types).
++ charsplusplus charsPrint a ‘+’ symbol for nonzero matrix elements and a space for zero matrix elements. This format can be very useful for examining the structure of a large sparse matrix.
The optional argument chars specifies a list of 3 characters to use
for printing values greater than zero, less than zero and equal to zero.
For example, with the ‘+ "+-."’ format, [1, 0, -1; -1, 0, 1]
is displayed as
ans = +.- -.+ |
bankPrint in a fixed format with two digits to the right of the decimal point.
native-hexPrint the hexadecimal representation of numbers as they are stored in
memory. For example, on a workstation which stores 8 byte real values
in IEEE format with the least significant byte first, the value of
pi when printed in native-hex format is
400921fb54442d18.
hexThe same as native-hex, but always print the most significant
byte first.
native-bitPrint the bit representation of numbers as stored in memory.
For example, the value of pi is
01000000000010010010000111111011 01010100010001000010110100011000 |
(shown here in two 32 bit sections for typesetting purposes) when printed in native-bit format on a workstation which stores 8 byte real values in IEEE format with the least significant byte first.
bitThe same as native-bit, but always print the most significant
bits first.
ratPrint a rational approximation, i.e., values are approximated
as the ratio of small integers.
For example, with the ‘rat’ format,
pi is displayed as 355/113.
The following two options affect the display of all matrices.
compactRemove blank lines around column number labels and between matrices producing more compact output with more data per page.
looseInsert blank lines above and below column number labels and between matrices to produce a more readable output with less data per page. (default).
See also: fixed_point_format, output_max_field_width, output_precision, split_long_rows, rats.
| 14.1.1.1 Paging Screen Output |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
When running interactively, Octave normally sends any output intended
for your terminal that is more than one screen long to a paging program,
such as less or more. This avoids the problem of having a
large volume of output stream by before you can read it. With
less (and some versions of more) you can also scan forward
and backward, and search for specific items.
Normally, no output is displayed by the pager until just before Octave
is ready to print the top level prompt, or read from the standard input
(for example, by using the fscanf or scanf functions).
This means that there may be some delay before any output appears on
your screen if you have asked Octave to perform a significant amount of
work with a single command statement. The function fflush may be
used to force output to be sent to the pager (or any other stream)
immediately.
You can select the program to run as the pager using the PAGER
function, and you can turn paging off by using the function
more.
Turn output pagination on or off. Without an argument, more
toggles the current state.
The current state can be determined via page_screen_output.
See also: page_screen_output, page_output_immediately, PAGER, PAGER_FLAGS.
Query or set the internal variable that specifies the program to use
to display terminal output on your system. The default value is
normally "less", "more", or
"pg", depending on what programs are installed on your system.
See section Installing Octave.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: PAGER_FLAGS, page_output_immediately, more, page_screen_output.
Query or set the internal variable that specifies the options to pass to the pager.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: PAGER, more, page_screen_output, page_output_immediately.
Query or set the internal variable that controls whether output intended
for the terminal window that is longer than one page is sent through a
pager. This allows you to view one screenful at a time. Some pagers
(such as less—see Installing Octave) are also capable of moving
backward on the output.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: more, page_output_immediately, PAGER, PAGER_FLAGS.
Query or set the internal variable that controls whether Octave sends output to the pager as soon as it is available. Otherwise, Octave buffers its output and waits until just before the prompt is printed to flush it to the pager.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: page_screen_output, more, PAGER, PAGER_FLAGS.
Flush output to fid. This is useful for ensuring that all
pending output makes it to the screen before some other event occurs.
For example, it is always a good idea to flush the standard output
stream before calling input.
fflush returns 0 on success and an OS dependent error value
(-1 on Unix) on error.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave has three functions that make it easy to prompt users for
input. The input and menu functions are normally
used for managing an interactive dialog with a user, and the
keyboard function is normally used for doing simple debugging.
Print prompt and wait for user input.
For example,
input ("Pick a number, any number! ")
|
prints the prompt
Pick a number, any number! |
and waits for the user to enter a value. The string entered by the user is evaluated as an expression, so it may be a literal constant, a variable name, or any other valid expression.
Currently, input only returns one value, regardless of the number
of values produced by the evaluation of the expression.
If you are only interested in getting a literal string value, you can
call input with the character string "s" as the second
argument. This tells Octave to return the string entered by the user
directly, without evaluating it first.
Because there may be output waiting to be displayed by the pager, it is
a good idea to always call fflush (stdout) before calling
input. This will ensure that all pending output is written to
the screen before your prompt.
Print a title string followed by a series of options. Each option will be printed along with a number. The return value is the number of the option selected by the user. This function is useful for interactive programs. There is no limit to the number of options that may be passed in, but it may be confusing to present more than will fit easily on one screen.
Ask the user a yes-or-no question.
Return logical true if the answer is yes or false if the answer is no.
Takes one argument, prompt, which is the string to display when asking
the question. prompt should end in a space; yes-or-no adds the
string ‘(yes or no) ’ to it. The user must confirm the answer with
<RET> and can edit it until it has been confirmed.
See also: input.
For input, the normal command line history and editing functions
are available at the prompt.
Octave also has a function that makes it possible to get a single character from the keyboard without requiring the user to type a carriage return.
Read a single keystroke from the keyboard. If called with an argument, don’t wait for a keypress. For example,
x = kbhit (); |
will set x to the next character typed at the keyboard as soon as it is typed.
x = kbhit (1); |
is identical to the above example, but doesn’t wait for a keypress, returning the empty string if no key is available.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The save and load commands allow data to be written to and
read from disk files in various formats. The default format of files
written by the save command can be controlled using the functions
save_default_options and save_precision.
As an example the following code creates a 3-by-3 matrix and saves it to the file ‘myfile.mat’.
A = [ 1:3; 4:6; 7:9 ]; save myfile.mat A |
Once one or more variables have been saved to a file, they can be
read into memory using the load command.
load myfile.mat
A
-| A =
-|
-| 1 2 3
-| 4 5 6
-| 7 8 9
|
Save the named variables v1, v2, …, in the file
file. The special filename ‘-’ may be used to write
output to the terminal. If no variable names are listed, Octave saves
all the variables in the current scope. Otherwise, full variable names or
pattern syntax can be used to specify the variables to save.
If the ‘-struct’ modifier is used, fields f1 f2 …
of the scalar structure STRUCT are saved as if they were variables
with corresponding names.
Valid options for the save command are listed in the following table.
Options that modify the output format override the format specified by
save_default_options.
If save is invoked using the functional form
save ("-option1", …, "file", "v1", …)
|
then the options, file, and variable name arguments (v1, …) must be specified as character strings.
-appendAppend to the destination instead of overwriting.
-asciiSave a single matrix in a text file without header or any other information.
-binarySave the data in Octave’s binary data format.
-float-binarySave the data in Octave’s binary data format but only using single precision. Only use this format if you know that all the values to be saved can be represented in single precision.
-hdf5Save the data in HDF5 format. (HDF5 is a free, portable binary format developed by the National Center for Supercomputing Applications at the University of Illinois.) This format is only available if Octave was built with a link to the HDF5 libraries.
-float-hdf5Save the data in HDF5 format but only using single precision. Only use this format if you know that all the values to be saved can be represented in single precision.
-V7-v7-7-mat7-binarySave the data in MATLAB’s v7 binary data format.
-V6-v6-6-mat-mat-binarySave the data in MATLAB’s v6 binary data format.
-V4-v4-4-mat4-binarySave the data in the binary format written by MATLAB version 4.
-textSave the data in Octave’s text data format. (default).
-zip-zUse the gzip algorithm to compress the file. This works equally on files that are compressed with gzip outside of octave, and gzip can equally be used to convert the files for backward compatibility. This option is only available if Octave was built with a link to the zlib libraries.
The list of variables to save may use wildcard patterns containing the following special characters:
?Match any single character.
*Match zero or more characters.
[ list ]Match the list of characters specified by list. If the first
character is ! or ^, match all characters except those
specified by list. For example, the pattern [a-zA-Z] will
match all lower and uppercase alphabetic characters.
Wildcards may also be used in the field name specifications when using the ‘-struct’ modifier (but not in the struct name itself).
Except when using the MATLAB binary data file format or the ‘-ascii’ format, saving global variables also saves the global status of the variable. If the variable is restored at a later time using ‘load’, it will be restored as a global variable.
The command
save -binary data a b* |
saves the variable ‘a’ and all variables beginning with ‘b’ to the file ‘data’ in Octave’s binary format.
See also: load, save_default_options, save_header_format_string, dlmread, csvread, fread.
There are three functions that modify the behavior of save.
Query or set the internal variable that specifies the default options
for the save command, and defines the default format.
Typical values include "-ascii", "-text -zip".
The default value is ‘-text’.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: save.
Query or set the internal variable that specifies the number of digits to keep when saving data in text format.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
Query or set the internal variable that specifies the format
string used for the comment line written at the beginning of
text-format data files saved by Octave. The format string is
passed to strftime and should begin with the character
‘#’ and contain no newline characters. If the value of
save_header_format_string is the empty string,
the header comment is omitted from text-format data files. The
default value is
"# Created by Octave VERSION, %a %b %d %H:%M:%S %Y %Z <USER@HOST>" |
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
Load the named variables v1, v2, …, from the file
file. If no variables are specified then all variables found in the
file will be loaded. As with save, the list of variables to extract
can be full names or use a pattern syntax. The format of the file is
automatically detected but may be overridden by supplying the appropriate
option.
If load is invoked using the functional form
load ("-option1", …, "file", "v1", …)
|
then the options, file, and variable name arguments (v1, …) must be specified as character strings.
If a variable that is not marked as global is loaded from a file when a global symbol with the same name already exists, it is loaded in the global symbol table. Also, if a variable is marked as global in a file and a local symbol exists, the local symbol is moved to the global symbol table and given the value from the file.
If invoked with a single output argument, Octave returns data instead
of inserting variables in the symbol table. If the data file contains
only numbers (TAB- or space-delimited columns), a matrix of values is
returned. Otherwise, load returns a structure with members
corresponding to the names of the variables in the file.
The load command can read data stored in Octave’s text and
binary formats, and MATLAB’s binary format. If compiled with zlib
support, it can also load gzip-compressed files. It will automatically
detect the type of file and do conversion from different floating point
formats (currently only IEEE big and little endian, though other formats
may be added in the future).
Valid options for load are listed in the following table.
-forceThis option is accepted for backward compatibility but is ignored. Octave now overwrites variables currently in memory with those of the same name found in the file.
-asciiForce Octave to assume the file contains columns of numbers in text format without any header or other information. Data in the file will be loaded as a single numeric matrix with the name of the variable derived from the name of the file.
-binaryForce Octave to assume the file is in Octave’s binary format.
-hdf5Force Octave to assume the file is in HDF5 format. (HDF5 is a free, portable binary format developed by the National Center for Supercomputing Applications at the University of Illinois.) Note that Octave can read HDF5 files not created by itself, but may skip some datasets in formats that it cannot support. This format is only available if Octave was built with a link to the HDF5 libraries.
-importThis option is accepted for backward compatibility but is ignored. Octave can now support multi-dimensional HDF data and automatically modifies variable names if they are invalid Octave identifiers.
-mat-mat-binary-6-v6-7-v7Force Octave to assume the file is in MATLAB’s version 6 or 7 binary format.
-mat4-binary-4-v4-V4Force Octave to assume the file is in the binary format written by MATLAB version 4.
-textForce Octave to assume the file is in Octave’s text format.
Read the contents of filename and return it as a string.
Return the native floating point format as a string
It is possible to write data to a file in a similar way to the
disp function for writing data to the screen. The fdisp
works just like disp except its first argument is a file pointer
as created by fopen. As an example, the following code writes
to data ‘myfile.txt’.
fid = fopen ("myfile.txt", "w");
fdisp (fid, "3/8 is ");
fdisp (fid, 3/8);
fclose (fid);
|
See section Opening and Closing Files, for details on how to use fopen
and fclose.
Display the value of x on the stream fid. For example:
fdisp (stdout, "The value of pi is:"), fdisp (stdout, pi)
-| the value of pi is:
-| 3.1416
|
Note that the output from fdisp always ends with a newline.
See also: disp.
Octave can also read and write matrices text files such as comma separated lists.
Write the matrix M to the named file using delimiters.
file should be a file name or writable file ID given by fopen.
The parameter delim specifies the delimiter to use to separate values on a row.
The value of r specifies the number of delimiter-only lines to add to the start of the file.
The value of c specifies the number of delimiters to prepend to each line of data.
If the argument "-append" is given, append to the end of
file.
In addition, the following keyword value pairs may appear at the end of the argument list:
"append"Either "on" or "off". See "-append" above.
"delimiter"See delim above.
"newline"The character(s) to use to separate each row. Three special cases
exist for this option. "unix" is changed into "n",
"pc" is changed into "rn", and "mac" is changed
into "r". Other values for this option are kept as is.
"roffset"See r above.
"coffset"See c above.
"precision"The precision to use when writing the file. It can either be a format string (as used by fprintf) or a number of significant digits.
dlmwrite ("file.csv", reshape (1:16, 4, 4));
|
dlmwrite ("file.tex", a, "delimiter", "&", "newline", "\\n")
|
Read the matrix data from a text file. If not defined the separator between fields is determined from the file itself. Otherwise the separation character is defined by sep.
Given two scalar arguments r0 and c0, these define the starting row and column of the data to be read. These values are indexed from zero, such that the first row corresponds to an index of zero.
The range parameter may be a 4-element vector containing the upper
left and lower right corner [R0,C0,R1,C1]
where the lowest index value is zero. Alternatively, a spreadsheet style
range such as "A2..Q15" or "T1:AA5" can be used. The
lowest alphabetical index 'A' refers to the first column. The
lowest row index is 1.
file should be a file name or file id given by fopen. In the
latter case, the file is read until end of file is reached.
The "emptyvalue" option may be used to specify the value used to
fill empty fields. The default is zero.
Write the matrix x to the file filename in comma-separated-value format.
This function is equivalent to
dlmwrite (filename, x, ",", …) |
Read the comma-separated-value file filename into the matrix x.
This function is equivalent to
x = dlmread (filename, "," , …) |
Formatted data from can be read from, or written to, text files as well.
Read data from a text file.
The file filename is read and parsed according to format. The
function behaves like strread except it works by parsing a file
instead of a string. See the documentation of strread for details.
In addition to the options supported by strread, this function
supports two more:
"headerlines":
The first value number of lines of filename are skipped.
"endofline":
Specify a single character or "rn". If no value is given, it
will be inferred from the file. If set to "" (empty string) EOLs are
ignored as delimiters.
The optional input n specifies the number of data lines to read; in this sense it differs slightly from the format repeat count in strread.
If the format string is empty (not: omitted) and the file contains only numeric data (excluding headerlines), textread will return a rectangular matrix with the number of columns matching the number of numeric fields on the first data line of the file. Empty fields are returned as zero values.
Read data from a text file or string.
The string str or file associated with fid is read from and
parsed according to format. The function behaves like strread
except it can also read from file instead of a string. See the documentation
of strread for details.
In addition to the options supported by strread, this function
supports a few more:
"collectoutput":
A value of 1 or true instructs textscan to concatenate consecutive columns
of the same class in the output cell array. A value of 0 or false (default)
leaves output in distinct columns.
"endofline":
Specify "r", "n" or "rn" (for CR, LF, or
CRLF). If no value is given, it will be inferred from the file. If set
to "" (empty string) EOLs are ignored as delimiters and added to
whitespace.
"headerlines":
The first value number of lines of fid are skipped.
"returnonerror":
If set to numerical 1 or true (default), return normally when read errors
have been encountered. If set to 0 or false, return an error and no data.
As the string or file is read by columns rather than by rows, and because
textscan is fairly forgiving as regards read errors, setting this option
may have little or no actual effect.
When reading from a character string, optional input argument n specifies the number of times format should be used (i.e., to limit the amount of data read). When reading from file, n specifies the number of data lines to read; in this sense it differs slightly from the format repeat count in strread.
The output C is a cell array whose second dimension is determined by the number of format specifiers.
The second output, position, provides the position, in characters, from the beginning of the file.
If the format string is empty (not: omitted) and the file contains only numeric data (excluding headerlines), textscan will return data in a number of columns matching the number of numeric fields on the first data line of the file.
The importdata function has the ability to work with a wide
variety of data.
Import data from the file fname.
Input parameters:
\t for tab.
(Only valid for ASCII files)
Different file types are supported:
Import ASCII table using the specified number of header rows and the specified delimiter.
| 14.1.3.1 Saving Data on Unexpected Exits |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
If Octave for some reason exits unexpectedly it will by default save the
variables available in the workspace to a file in the current directory.
By default this file is named ‘octave-workspace’ and can be loaded
into memory with the load command. While the default behavior
most often is reasonable it can be changed through the following
functions.
Query or set the internal variable that controls whether Octave tries to save all current variables to the file ‘octave-workspace’ if it crashes or receives a hangup, terminate or similar signal.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: octave_core_file_limit, octave_core_file_name, octave_core_file_options.
Query or set the internal variable that controls whether Octave tries to save all current variables to the file ‘octave-workspace’ if it receives a hangup signal.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
Query or set the internal variable that controls whether Octave tries to save all current variables to the file ‘octave-workspace’ if it receives a terminate signal.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
Query or set the internal variable that specifies the options used for
saving the workspace data if Octave aborts. The value of
octave_core_file_options should follow the same format as the
options for the save function. The default value is Octave’s binary
format.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: crash_dumps_octave_core, octave_core_file_name, octave_core_file_limit.
Query or set the internal variable that specifies the maximum amount of memory (in kilobytes) of the top-level workspace that Octave will attempt to save when writing data to the crash dump file (the name of the file is specified by octave_core_file_name). If octave_core_file_options flags specify a binary format, then octave_core_file_limit will be approximately the maximum size of the file. If a text file format is used, then the file could be much larger than the limit. The default value is -1 (unlimited)
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: crash_dumps_octave_core, octave_core_file_name, octave_core_file_options.
Query or set the internal variable that specifies the name of the file
used for saving data from the top-level workspace if Octave aborts.
The default value is "octave-workspace"
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: crash_dumps_octave_core, octave_core_file_name, octave_core_file_options.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave’s C-style input and output functions provide most of the functionality of the C programming language’s standard I/O library. The argument lists for some of the input functions are slightly different, however, because Octave has no way of passing arguments by reference.
In the following, file refers to a file name and fid refers
to an integer file number, as returned by fopen.
There are three files that are always available. Although these files can be accessed using their corresponding numeric file ids, you should always use the symbolic names given in the table below, since it will make your programs easier to understand.
Return the numeric value corresponding to the standard input stream. When Octave is used interactively, this is filtered through the command line editing functions.
Return the numeric value corresponding to the standard output stream. Data written to the standard output is normally filtered through the pager.
Return the numeric value corresponding to the standard error stream. Even if paging is turned on, the standard error is not sent to the pager. It is useful for error messages and prompts.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
When reading data from a file it must be opened for reading first, and
likewise when writing to a file. The fopen function returns a
pointer to an open file that is ready to be read or written. Once all
data has been read from or written to the opened file it should be closed.
The fclose function does this. The following code illustrates
the basic pattern for writing to a file, but a very similar pattern is
used when reading a file.
filename = "myfile.txt"; fid = fopen (filename, "w"); # Do the actual I/O here… fclose (fid); |
The first form of the fopen function opens the named file with
the specified mode (read-write, read-only, etc.) and architecture
interpretation (IEEE big endian, IEEE little endian, etc.), and returns
an integer value that may be used to refer to the file later. If an
error occurs, fid is set to -1 and msg contains the
corresponding system error message. The mode is a one or two
character string that specifies whether the file is to be opened for
reading, writing, or both.
The second form of the fopen function returns a vector of file ids
corresponding to all the currently open files, excluding the
stdin, stdout, and stderr streams.
The third form of the fopen function returns information about the
open file given its file id.
For example,
myfile = fopen ("splat.dat", "r", "ieee-le");
|
opens the file ‘splat.dat’ for reading. If necessary, binary numeric values will be read assuming they are stored in IEEE format with the least significant bit first, and then converted to the native representation.
Opening a file that is already open simply opens it again and returns a separate file id. It is not an error to open a file several times, though writing to the same file through several different file ids may produce unexpected results.
The possible values ‘mode’ may have are
Open a file for reading.
Open a file for writing. The previous contents are discarded.
Open or create a file for writing at the end of the file.
Open an existing file for reading and writing.
Open a file for reading or writing. The previous contents are discarded.
Open or create a file for reading or writing at the end of the file.
Append a "t" to the mode string to open the file in text mode or a
"b" to open in binary mode. On Windows and Macintosh systems, text
mode reading and writing automatically converts linefeeds to the
appropriate line end character for the system (carriage-return linefeed
on Windows, carriage-return on Macintosh). The default if no mode is
specified is binary mode.
Additionally, you may append a "z" to the mode string to open a
gzipped file for reading or writing. For this to be successful, you
must also open the file in binary mode.
The parameter arch is a string specifying the default data format for the file. Valid values for arch are:
The format of the current machine (this is the default).
IEEE big endian format.
IEEE little endian format.
however, conversions are currently only supported for ‘native’ ‘ieee-be’, and ‘ieee-le’ formats.
See also: fclose, fgets, fgetl, fscanf, fread, fputs, fdisp, fprintf, fwrite, fskipl, fseek, frewind, ftell, feof, ferror, fclear, fflush, freport.
Close the specified file. If successful, fclose returns 0,
otherwise, it returns -1. The second form of the fclose call closes
all open files except stdout, stderr, and stdin.
Return true if fid refers to an open file.
See also: fopen.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Once a file has been opened for writing a string can be written to the
file using the fputs function. The following example shows
how to write the string ‘Free Software is needed for Free Science’
to the file ‘free.txt’.
filename = "free.txt"; fid = fopen (filename, "w"); fputs (fid, "Free Software is needed for Free Science"); fclose (fid); |
Write a string to a file with no formatting.
Return a non-negative number on success and EOF on error.
A function much similar to fputs is available for writing data
to the screen. The puts function works just like fputs
except it doesn’t take a file pointer as its input.
Write a string to the standard output with no formatting.
Return a non-negative number on success and EOF on error.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
To read from a file it must be opened for reading using fopen.
Then a line can be read from the file using fgetl as the following
code illustrates
fid = fopen ("free.txt");
txt = fgetl (fid)
-| Free Software is needed for Free Science
fclose (fid);
|
This of course assumes that the file ‘free.txt’ exists and contains the line ‘Free Software is needed for Free Science’.
Read characters from a file, stopping after a newline, or EOF, or len characters have been read. The characters read, excluding the possible trailing newline, are returned as a string.
If len is omitted, fgetl reads until the next newline
character.
If there are no more characters to read, fgetl returns -1.
To read a line and return the terminating newline see fgets.
Read characters from a file, stopping after a newline, or EOF, or len characters have been read. The characters read, including the possible trailing newline, are returned as a string.
If len is omitted, fgets reads until the next newline
character.
If there are no more characters to read, fgets returns -1.
To read a line and discard the terminating newline see fgetl.
Read and skip count lines from the file descriptor fid.
fskipl discards characters until an end-of-line is encountered exactly
count-times, or until the end-of-file marker is found.
If count is omitted, it defaults to 1. count may also be
Inf, in which case lines are skipped until the end of the file.
This form is suitable for counting the number of lines in a file.
Returns the number of lines skipped (end-of-line sequences encountered).
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section describes how to call printf and related functions.
The following functions are available for formatted output. They are modeled after the C language functions of the same name, but they interpret the format template differently in order to improve the performance of printing vector and matrix values.
Print optional arguments under the control of the template string
template to the stream stdout and return the number of
characters printed.
See the Formatted Output section of the GNU Octave manual for a complete description of the syntax of the template string.
This function is just like printf, except that the output is
written to the stream fid instead of stdout.
If fid is omitted, the output is written to stdout.
See also: fputs, fdisp, fwrite, fscanf, printf, sprintf, fopen.
This is like printf, except that the output is returned as a
string. Unlike the C library function, which requires you to provide a
suitably sized string as an argument, Octave’s sprintf function
returns the string, automatically sized to hold all of the items
converted.
The printf function can be used to print any number of arguments.
The template string argument you supply in a call provides
information not only about the number of additional arguments, but also
about their types and what style should be used for printing them.
Ordinary characters in the template string are simply written to the output stream as-is, while conversion specifications introduced by a ‘%’ character in the template cause subsequent arguments to be formatted and written to the output stream. For example,
pct = 37;
filename = "foo.txt";
printf ("Processed %d%% of '%s'.\nPlease be patient.\n",
pct, filename);
|
produces output like
Processed 37% of 'foo.txt'. Please be patient. |
This example shows the use of the ‘%d’ conversion to specify that a scalar argument should be printed in decimal notation, the ‘%s’ conversion to specify printing of a string argument, and the ‘%%’ conversion to print a literal ‘%’ character.
There are also conversions for printing an integer argument as an unsigned value in octal, decimal, or hexadecimal radix (‘%o’, ‘%u’, or ‘%x’, respectively); or as a character value (‘%c’).
Floating-point numbers can be printed in normal, fixed-point notation using the ‘%f’ conversion or in exponential notation using the ‘%e’ conversion. The ‘%g’ conversion uses either ‘%e’ or ‘%f’ format, depending on what is more appropriate for the magnitude of the particular number.
You can control formatting more precisely by writing modifiers between the ‘%’ and the character that indicates which conversion to apply. These slightly alter the ordinary behavior of the conversion. For example, most conversion specifications permit you to specify a minimum field width and a flag indicating whether you want the result left- or right-justified within the field.
The specific flags and modifiers that are permitted and their interpretation vary depending on the particular conversion. They’re all described in more detail in the following sections.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
When given a matrix value, Octave’s formatted output functions cycle through the format template until all the values in the matrix have been printed. For example:
printf ("%4.2f %10.2e %8.4g\n", hilb (3));
-| 1.00 5.00e-01 0.3333
-| 0.50 3.33e-01 0.25
-| 0.33 2.50e-01 0.2
|
If more than one value is to be printed in a single call, the output functions do not return to the beginning of the format template when moving on from one value to the next. This can lead to confusing output if the number of elements in the matrices are not exact multiples of the number of conversions in the format template. For example:
printf ("%4.2f %10.2e %8.4g\n", [1, 2], [3, 4]);
-| 1.00 2.00e+00 3
-| 4.00
|
If this is not what you want, use a series of calls instead of just one.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section provides details about the precise syntax of conversion
specifications that can appear in a printf template
string.
Characters in the template string that are not part of a conversion specification are printed as-is to the output stream.
The conversion specifications in a printf template string have
the general form:
% flags width [ . precision ] type conversion |
For example, in the conversion specifier ‘%-10.8ld’, the ‘-’ is a flag, ‘10’ specifies the field width, the precision is ‘8’, the letter ‘l’ is a type modifier, and ‘d’ specifies the conversion style. (This particular type specifier says to print a numeric argument in decimal notation, with a minimum of 8 digits left-justified in a field at least 10 characters wide.)
In more detail, output conversion specifications consist of an initial ‘%’ character followed in sequence by:
You can also specify a field width of ‘*’. This means that the next argument in the argument list (before the actual value to be printed) is used as the field width. The value is rounded to the nearest integer. If the value is negative, this means to set the ‘-’ flag (see below) and to use the absolute value as the field width.
You can also specify a precision of ‘*’. This means that the next argument in the argument list (before the actual value to be printed) is used as the precision. The value must be an integer, and is ignored if it is negative.
printf function, but is recognized to provide
compatibility with the C language printf.
The exact options that are permitted and how they are interpreted vary between the different conversion specifiers. See the descriptions of the individual conversions for information about the particular options that they use.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Here is a table summarizing what all the different conversions do:
Print an integer as a signed decimal number. See section Integer Conversions, for details. ‘%d’ and ‘%i’ are synonymous for
output, but are different when used with scanf for input
(see section Table of Input Conversions).
Print an integer as an unsigned octal number. See section Integer Conversions, for details.
Print an integer as an unsigned decimal number. See section Integer Conversions, for details.
Print an integer as an unsigned hexadecimal number. ‘%x’ uses lowercase letters and ‘%X’ uses uppercase. See section Integer Conversions, for details.
Print a floating-point number in normal (fixed-point) notation. See section Floating-Point Conversions, for details.
Print a floating-point number in exponential notation. ‘%e’ uses lowercase letters and ‘%E’ uses uppercase. See section Floating-Point Conversions, for details.
Print a floating-point number in either normal (fixed-point) or exponential notation, whichever is more appropriate for its magnitude. ‘%g’ uses lowercase letters and ‘%G’ uses uppercase. See section Floating-Point Conversions, for details.
Print a single character. See section Other Output Conversions.
Print a string. See section Other Output Conversions.
Print a literal ‘%’ character. See section Other Output Conversions.
If the syntax of a conversion specification is invalid, unpredictable things will happen, so don’t do this. If there aren’t enough function arguments provided to supply values for all the conversion specifications in the template string, or if the arguments are not of the correct types, the results are unpredictable. If you supply more arguments than conversion specifications, the extra argument values are simply ignored; this is sometimes useful.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section describes the options for the ‘%d’, ‘%i’, ‘%o’, ‘%u’, ‘%x’, and ‘%X’ conversion specifications. These conversions print integers in various formats.
The ‘%d’ and ‘%i’ conversion specifications both print an numeric argument as a signed decimal number; while ‘%o’, ‘%u’, and ‘%x’ print the argument as an unsigned octal, decimal, or hexadecimal number (respectively). The ‘%X’ conversion specification is just like ‘%x’ except that it uses the characters ‘ABCDEF’ as digits instead of ‘abcdef’.
The following flags are meaningful:
Left-justify the result in the field (instead of the normal right-justification).
For the signed ‘%d’ and ‘%i’ conversions, print a plus sign if the value is positive.
For the signed ‘%d’ and ‘%i’ conversions, if the result doesn’t start with a plus or minus sign, prefix it with a space character instead. Since the ‘+’ flag ensures that the result includes a sign, this flag is ignored if you supply both of them.
For the ‘%o’ conversion, this forces the leading digit to be ‘0’, as if by increasing the precision. For ‘%x’ or ‘%X’, this prefixes a leading ‘0x’ or ‘0X’ (respectively) to the result. This doesn’t do anything useful for the ‘%d’, ‘%i’, or ‘%u’ conversions.
Pad the field with zeros instead of spaces. The zeros are placed after any indication of sign or base. This flag is ignored if the ‘-’ flag is also specified, or if a precision is specified.
If a precision is supplied, it specifies the minimum number of digits to appear; leading zeros are produced if necessary. If you don’t specify a precision, the number is printed with as many digits as it needs. If you convert a value of zero with an explicit precision of zero, then no characters at all are produced.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section discusses the conversion specifications for floating-point numbers: the ‘%f’, ‘%e’, ‘%E’, ‘%g’, and ‘%G’ conversions.
The ‘%f’ conversion prints its argument in fixed-point notation,
producing output of the form
[-]ddd.ddd,
where the number of digits following the decimal point is controlled
by the precision you specify.
The ‘%e’ conversion prints its argument in exponential notation,
producing output of the form
[-]d.ddde[+|-]dd.
Again, the number of digits following the decimal point is controlled by
the precision. The exponent always contains at least two digits. The
‘%E’ conversion is similar but the exponent is marked with the letter
‘E’ instead of ‘e’.
The ‘%g’ and ‘%G’ conversions print the argument in the style of ‘%e’ or ‘%E’ (respectively) if the exponent would be less than -4 or greater than or equal to the precision; otherwise they use the ‘%f’ style. Trailing zeros are removed from the fractional portion of the result and a decimal-point character appears only if it is followed by a digit.
The following flags can be used to modify the behavior:
Left-justify the result in the field. Normally the result is right-justified.
Always include a plus or minus sign in the result.
If the result doesn’t start with a plus or minus sign, prefix it with a space instead. Since the ‘+’ flag ensures that the result includes a sign, this flag is ignored if you supply both of them.
Specifies that the result should always include a decimal point, even if no digits follow it. For the ‘%g’ and ‘%G’ conversions, this also forces trailing zeros after the decimal point to be left in place where they would otherwise be removed.
Pad the field with zeros instead of spaces; the zeros are placed after any sign. This flag is ignored if the ‘-’ flag is also specified.
The precision specifies how many digits follow the decimal-point
character for the ‘%f’, ‘%e’, and ‘%E’ conversions. For
these conversions, the default precision is 6. If the precision
is explicitly 0, this suppresses the decimal point character
entirely. For the ‘%g’ and ‘%G’ conversions, the precision
specifies how many significant digits to print. Significant digits are
the first digit before the decimal point, and all the digits after it.
If the precision is 0 or not specified for ‘%g’ or
‘%G’, it is treated like a value of 1. If the value being
printed cannot be expressed precisely in the specified number of digits,
the value is rounded to the nearest number that fits.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section describes miscellaneous conversions for printf.
The ‘%c’ conversion prints a single character. The ‘-’ flag can be used to specify left-justification in the field, but no other flags are defined, and no precision or type modifier can be given. For example:
printf ("%c%c%c%c%c", "h", "e", "l", "l", "o");
|
prints ‘hello’.
The ‘%s’ conversion prints a string. The corresponding argument must be a string. A precision can be specified to indicate the maximum number of characters to write; otherwise characters in the string up to but not including the terminating null character are written to the output stream. The ‘-’ flag can be used to specify left-justification in the field, but no other flags or type modifiers are defined for this conversion. For example:
printf ("%3s%-6s", "no", "where");
|
prints ‘ nowhere ’ (note the leading and trailing spaces).
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave provides the scanf, fscanf, and sscanf
functions to read formatted input. There are two forms of each of these
functions. One can be used to extract vectors of data from a file, and
the other is more ‘C-like’.
In the first form, read from fid according to template, returning the result in the matrix val.
The optional argument size specifies the amount of data to read and may be one of
InfRead as much as possible, returning a column vector.
nrRead up to nr elements, returning a column vector.
[nr, Inf]Read as much as possible, returning a matrix with nr rows. If the number of elements read is not an exact multiple of nr, the last column is padded with zeros.
[nr, nc]Read up to nr * nc elements, returning a matrix with
nr rows. If the number of elements read is not an exact multiple
of nr, the last column is padded with zeros.
If size is omitted, a value of Inf is assumed.
A string is returned if template specifies only character conversions.
The number of items successfully read is returned in count.
If an error occurs, errmsg contains a system-dependent error message.
In the second form, read from fid according to template, with each conversion specifier in template corresponding to a single scalar return value. This form is more “C-like”, and also compatible with previous versions of Octave. The number of successful conversions is returned in count
See the Formatted Input section of the GNU Octave manual for a complete description of the syntax of the template string.
This is equivalent to calling fscanf with fid = stdin.
It is currently not useful to call scanf in interactive
programs.
This is like fscanf, except that the characters are taken from the
string string instead of from a stream. Reaching the end of the
string is treated as an end-of-file condition. In addition to the values
returned by fscanf, the index of the next character to be read
is returned in pos.
Calls to scanf are superficially similar to calls to
printf in that arbitrary arguments are read under the control of
a template string. While the syntax of the conversion specifications in
the template is very similar to that for printf, the
interpretation of the template is oriented more towards free-format
input and simple pattern matching, rather than fixed-field formatting.
For example, most scanf conversions skip over any amount of
“white space” (including spaces, tabs, and newlines) in the input
file, and there is no concept of precision for the numeric input
conversions as there is for the corresponding output conversions.
Ordinarily, non-whitespace characters in the template are expected to
match characters in the input stream exactly.
When a matching failure occurs, scanf returns immediately,
leaving the first non-matching character as the next character to be
read from the stream, and scanf returns all the items that were
successfully converted.
The formatted input functions are not used as frequently as the formatted output functions. Partly, this is because it takes some care to use them properly. Another reason is that it is difficult to recover from a matching error.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A scanf template string is a string that contains ordinary
multibyte characters interspersed with conversion specifications that
start with ‘%’.
Any whitespace character in the template causes any number of whitespace characters in the input stream to be read and discarded. The whitespace characters that are matched need not be exactly the same whitespace characters that appear in the template string. For example, write ‘ , ’ in the template to recognize a comma with optional whitespace before and after.
Other characters in the template string that are not part of conversion specifications must match characters in the input stream exactly; if this is not the case, a matching failure occurs.
The conversion specifications in a scanf template string
have the general form:
% flags width type conversion |
In more detail, an input conversion specification consists of an initial ‘%’ character followed in sequence by:
scanf finds a conversion
specification that uses this flag, it reads input as directed by the
rest of the conversion specification, but it discards this input, does
not return any value, and does not increment the count of
successful assignments.
scanf function, but is recognized to provide
compatibility with the C language scanf.
The exact options that are permitted and how they are interpreted vary between the different conversion specifiers. See the descriptions of the individual conversions for information about the particular options that they allow.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Here is a table that summarizes the various conversion specifications:
Matches an optionally signed integer written in decimal. See section Numeric Input Conversions.
Matches an optionally signed integer in any of the formats that the C language defines for specifying an integer constant. See section Numeric Input Conversions.
Matches an unsigned integer written in octal radix. See section Numeric Input Conversions.
Matches an unsigned integer written in decimal radix. See section Numeric Input Conversions.
Matches an unsigned integer written in hexadecimal radix. See section Numeric Input Conversions.
Matches an optionally signed floating-point number. See section Numeric Input Conversions.
Matches a string containing only non-whitespace characters. See section String Input Conversions.
Matches a string of one or more characters; the number of characters read is controlled by the maximum field width given for the conversion. See section String Input Conversions.
This matches a literal ‘%’ character in the input stream. No corresponding argument is used.
If the syntax of a conversion specification is invalid, the behavior is undefined. If there aren’t enough function arguments provided to supply addresses for all the conversion specifications in the template strings that perform assignments, or if the arguments are not of the correct types, the behavior is also undefined. On the other hand, extra arguments are simply ignored.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section describes the scanf conversions for reading numeric
values.
The ‘%d’ conversion matches an optionally signed integer in decimal radix.
The ‘%i’ conversion matches an optionally signed integer in any of the formats that the C language defines for specifying an integer constant.
For example, any of the strings ‘10’, ‘0xa’, or ‘012’
could be read in as integers under the ‘%i’ conversion. Each of
these specifies a number with decimal value 10.
The ‘%o’, ‘%u’, and ‘%x’ conversions match unsigned integers in octal, decimal, and hexadecimal radices, respectively.
The ‘%X’ conversion is identical to the ‘%x’ conversion. They both permit either uppercase or lowercase letters to be used as digits.
Unlike the C language scanf, Octave ignores the ‘h’,
‘l’, and ‘L’ modifiers.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section describes the scanf input conversions for reading
string and character values: ‘%s’ and ‘%c’.
The ‘%c’ conversion is the simplest: it matches a fixed number of characters, always. The maximum field with says how many characters to read; if you don’t specify the maximum, the default is 1. This conversion does not skip over initial whitespace characters. It reads precisely the next n characters, and fails if it cannot get that many.
The ‘%s’ conversion matches a string of non-whitespace characters. It skips and discards initial whitespace, but stops when it encounters more whitespace after having read something.
For example, reading the input:
hello, world |
with the conversion ‘%10c’ produces " hello, wo", but
reading the same input with the conversion ‘%10s’ produces
"hello,".
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave can read and write binary data using the functions fread
and fwrite, which are patterned after the standard C functions
with the same names. They are able to automatically swap the byte order
of integer data and convert among the supported floating point formats
as the data are read.
Read binary data of type precision from the specified file ID fid.
The optional argument size specifies the amount of data to read and may be one of
InfRead as much as possible, returning a column vector.
nrRead up to nr elements, returning a column vector.
[nr, Inf]Read as much as possible, returning a matrix with nr rows. If the number of elements read is not an exact multiple of nr, the last column is padded with zeros.
[nr, nc]Read up to nr * nc elements, returning a matrix with
nr rows. If the number of elements read is not an exact multiple
of nr, the last column is padded with zeros.
If size is omitted, a value of Inf is assumed.
The optional argument precision is a string specifying the type of data to read and may be one of
"schar""signed char"Signed character.
"uchar""unsigned char"Unsigned character.
"int8""integer*1"8-bit signed integer.
"int16""integer*2"16-bit signed integer.
"int32""integer*4"32-bit signed integer.
"int64""integer*8"64-bit signed integer.
"uint8"8-bit unsigned integer.
"uint16"16-bit unsigned integer.
"uint32"32-bit unsigned integer.
"uint64"64-bit unsigned integer.
"single""float32""real*4"32-bit floating point number.
"double""float64""real*8"64-bit floating point number.
"char""char*1"Single character.
"short"Short integer (size is platform dependent).
"int"Integer (size is platform dependent).
"long"Long integer (size is platform dependent).
"ushort""unsigned short"Unsigned short integer (size is platform dependent).
"uint""unsigned int"Unsigned integer (size is platform dependent).
"ulong""unsigned long"Unsigned long integer (size is platform dependent).
"float"Single precision floating point number (size is platform dependent).
The default precision is "uchar".
The precision argument may also specify an optional repeat
count. For example, ‘32*single’ causes fread to read
a block of 32 single precision floating point numbers. Reading in
blocks is useful in combination with the skip argument.
The precision argument may also specify a type conversion.
For example, ‘int16=>int32’ causes fread to read 16-bit
integer values and return an array of 32-bit integer values. By
default, fread returns a double precision array. The special
form ‘*TYPE’ is shorthand for ‘TYPE=>TYPE’.
The conversion and repeat counts may be combined. For example, the
specification ‘32*single=>single’ causes fread to read
blocks of single precision floating point values and return an array
of single precision values instead of the default array of double
precision values.
The optional argument skip specifies the number of bytes to skip after each element (or block of elements) is read. If it is not specified, a value of 0 is assumed. If the final block read is not complete, the final skip is omitted. For example,
fread (f, 10, "3*single=>single", 8) |
will omit the final 8-byte skip because the last read will not be a complete block of 3 values.
The optional argument arch is a string specifying the data format for the file. Valid values are
"native"The format of the current machine.
"ieee-be"IEEE big endian.
"ieee-le"IEEE little endian.
The data read from the file is returned in val, and the number of
values read is returned in count
Write data in binary form of type precision to the specified file ID fid, returning the number of values successfully written to the file.
The argument data is a matrix of values that are to be written to the file. The values are extracted in column-major order.
The remaining arguments precision, skip, and arch are
optional, and are interpreted as described for fread.
The behavior of fwrite is undefined if the values in data
are too large to fit in the specified precision.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Sometimes one needs to write data to a file that is only temporary. This is most commonly used when an external program launched from within Octave needs to access data. When Octave exits all temporary files will be deleted, so this step need not be executed manually.
Return the file ID corresponding to a new temporary file with a unique
name created from template. The last six characters of template
must be XXXXXX and these are replaced with a string that makes the
filename unique. The file is then created with mode read/write and
permissions that are system dependent (on GNU/Linux systems, the permissions
will be 0600 for versions of glibc 2.0.7 and later). The file is opened
in binary mode and with the O_EXCL flag.
If the optional argument delete is supplied and is true, the file will be deleted automatically when Octave exits.
If successful, fid is a valid file ID, name is the name of the file, and msg is an empty string. Otherwise, fid is -1, name is empty, and msg contains a system-dependent error message.
Return the file ID corresponding to a new temporary file with a unique
name. The file is opened in binary read/write ("w+b") mode.
The file will be deleted automatically when it is closed or when Octave
exits.
If successful, fid is a valid file ID and msg is an empty string. Otherwise, fid is -1 and msg contains a system-dependent error message.
Return a unique temporary file name as a string.
If prefix is omitted, a value of "oct-" is used.
If dir is also omitted, the default directory for temporary files
is used. If dir is provided, it must exist, otherwise the default
directory for temporary files is used. Since the named file is not
opened, by tmpnam, it is possible (though relatively unlikely)
that it will not be available by the time your program attempts to open it.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Once a file has been opened its status can be acquired. As an example
the feof functions determines if the end of the file has been
reached. This can be very useful when reading small parts of a file
at a time. The following example shows how to read one line at a time
from a file until the end has been reached.
filename = "myfile.txt"; fid = fopen (filename, "r"); while (! feof (fid) ) text_line = fgetl (fid); endwhile fclose (fid); |
Note that in some situations it is more efficient to read the entire contents of a file and then process it, than it is to read it line by line. This has the potential advantage of removing the loop in the above code.
Return 1 if an end-of-file condition has been encountered for a given file and 0 otherwise. Note that it will only return 1 if the end of the file has already been encountered, not if the next read operation will result in an end-of-file condition.
Return 1 if an error condition has been encountered for the file ID fid and 0 otherwise. Note that it will only return 1 if an error has already been encountered, not if the next operation will result in an error condition.
The second argument is optional. If it is supplied, also clear the error condition.
Clear the stream state for the specified file.
See also: fopen.
Print a list of which files have been opened, and whether they are open for reading, writing, or both. For example:
freport ()
-| number mode name
-|
-| 0 r stdin
-| 1 w stdout
-| 2 w stderr
-| 3 r myfile
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Three functions are available for setting and determining the position of the file pointer for a given file.
Return the position of the file pointer as the number of characters from the beginning of the file fid.
Set the file pointer to any location within the file fid.
The pointer is positioned offset characters from the origin,
which may be one of the predefined variables SEEK_CUR (current
position), SEEK_SET (beginning), or SEEK_END (end of
file) or strings "cof", "bof" or "eof". If
origin is omitted, SEEK_SET is assumed. offset may
be positive, negative, or zero but not all combinations of origin and
offset can be realized.
Return 0 on success and -1 on error.
Return the numerical value to pass to fseek to perform
one of the following actions:
SEEK_SETPosition file relative to the beginning.
SEEK_CURPosition file relative to the current position.
SEEK_ENDPosition file relative to the end.
See also: fseek.
Move the file pointer to the beginning of the file fid, returning
0 for success, and -1 if an error was encountered. It is equivalent to
fseek (fid, 0, SEEK_SET).
The following example stores the current file position in the variable
marker, moves the pointer to the beginning of the file, reads
four characters, and then returns to the original position.
marker = ftell (myfile); frewind (myfile); fourch = fgets (myfile, 4); fseek (myfile, marker, SEEK_SET); |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 15.1 Introduction to Plotting | ||
| 15.2 High-Level Plotting | ||
| 15.3 Graphics Data Structures | ||
| 15.4 Advanced Plotting |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Earlier versions of Octave provided plotting through the use of
gnuplot. This capability is still available. But, a newer plotting
capability is provided by access to OpenGL. Which plotting system
is used is controlled by the graphics_toolkit function.
See section Graphics Toolkits.
The function call graphics_toolkit ("fltk") selects the
FLTK/OpenGL system, and graphics_toolkit ("gnuplot") selects the
gnuplot system. The two systems may be used selectively through the use
of the graphics_toolkit property of the graphics handle for each
figure. This is explained in Graphics Data Structures.
Caution: The FLTK toolkit uses single precision variables internally
which limits the maximum value that can be displayed to approximately
10^38. If your data contains larger values you must use the gnuplot
toolkit which supports values up to 10^308.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave provides simple means to create many different types of two- and three-dimensional plots using high-level functions.
If you need more detailed control, see Graphics Data Structures and Advanced Plotting.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 15.2.1.1 Axis Configuration | ||
| 15.2.1.2 Two-dimensional Function Plotting | ||
| 15.2.1.3 Two-dimensional Geometric Shapes |
The plot function allows you to create simple x-y plots with
linear axes. For example,
x = -10:0.1:10; plot (x, sin (x)); |
displays a sine wave shown in fig:plot. On most systems, this command will open a separate plot window to display the graph.
Figure 15.1: Simple Two-Dimensional Plot.
Produce 2-D plots.
Many different combinations of arguments are possible. The simplest form is
plot (y) |
where the argument is taken as the set of y coordinates and the
x coordinates are taken to be the range 1:numel (y).
If more than one argument is given, they are interpreted as
plot (y, property, value, …) |
or
plot (x, y, property, value, …) |
or
plot (x, y, fmt, …) |
and so on. Any number of argument sets may appear. The x and y values are interpreted as follows:
squeeze() is applied to arguments with more than two dimensions,
but no more than two singleton dimensions.
Multiple property-value pairs may be specified, but they must appear
in pairs. These arguments are applied to the line objects drawn by
plot. Useful properties to modify are "linestyle",
"linewidth", "color", "marker",
"markersize", "markeredgecolor", "markerfacecolor".
The fmt format argument can also be used to control the plot style.
The format is composed of three parts: linestyle, markerstyle, color.
When a markerstyle is specified, but no linestyle, only the markers are
plotted. Similarly, if a linestyle is specified, but no markerstyle, then
only lines are drawn. If both are specified then lines and markers will
be plotted. If no fmt and no property/value pairs are
given, then the default plot style is solid lines with no markers and the
color determined by the "colororder" property of the current axes.
Format arguments:
| ‘-’ | Use solid lines (default). |
| ‘--’ | Use dashed lines. |
| ‘:’ | Use dotted lines. |
| ‘-.’ | Use dash-dotted lines. |
| ‘+’ | crosshair |
| ‘o’ | circle |
| ‘*’ | star |
| ‘.’ | point |
| ‘x’ | cross |
| ‘s’ | square |
| ‘d’ | diamond |
| ‘^’ | upward-facing triangle |
| ‘v’ | downward-facing triangle |
| ‘>’ | right-facing triangle |
| ‘<’ | left-facing triangle |
| ‘p’ | pentagram |
| ‘h’ | hexagram |
| ‘k’ | blacK |
| ‘r’ | Red |
| ‘g’ | Green |
| ‘b’ | Blue |
| ‘m’ | Magenta |
| ‘c’ | Cyan |
| ‘w’ | White |
";key;"Here "key" is the label to use for the plot legend.
The fmt argument may also be used to assign legend keys.
To do so, include the desired label between semicolons after the
formatting sequence described above, e.g., "+b;Key Title;".
Note that the last semicolon is required and Octave will generate
an error if it is left out.
Here are some plot examples:
plot (x, y, "or", x, y2, x, y3, "m", x, y4, "+") |
This command will plot y with red circles, y2 with solid
lines, y3 with solid magenta lines, and y4 with points
displayed as ‘+’.
plot (b, "*", "markersize", 10) |
This command will plot the data in the variable b,
with points displayed as ‘*’ and a marker size of 10.
t = 0:0.1:6.3; plot (t, cos(t), "-;cos(t);", t, sin(t), "-b;sin(t);"); |
This will plot the cosine and sine functions and label them accordingly in the legend.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a vector of graphics handles to the created line objects.
To save a plot, in one of several image formats such as PostScript
or PNG, use the print command.
See also: axis, box, grid, hold, legend, title, xlabel, ylabel, xlim, ylim, ezplot, errorbar, fplot, line, plot3, polar, loglog, semilogx, semilogy, subplot.
The plotyy function may be used to create a plot with two
independent y axes.
Plot two sets of data with independent y-axes.
The arguments x1 and y1 define the arguments for the first plot and x1 and y2 for the second.
By default the arguments are evaluated with
feval (@plot, x, y). However the type of plot can be
modified with the fun argument, in which case the plots are
generated by feval (fun, x, y). fun can be
a function handle, an inline function, or a string of a function name.
The function to use for each of the plots can be independently defined with fun1 and fun2.
If the first argument hax is an axes handle, then it defines the principal axis in which to plot the x1 and y1 data.
The return value ax is a vector with the axis handles of the two y axes. h1 and h2 are handles to the objects generated by the plot commands.
x = 0:0.1:2*pi;
y1 = sin (x);
y2 = exp (x - 1);
ax = plotyy (x, y1, x - 1, y2, @plot, @semilogy);
xlabel ("X");
ylabel (ax(1), "Axis 1");
ylabel (ax(2), "Axis 2");
|
See also: plot.
The functions semilogx, semilogy, and loglog are
similar to the plot function, but produce plots in which one or
both of the axes use log scales.
Produce a 2-D plot using a logarithmic scale for the x-axis.
See the documentation of plot for a description of the
arguments that semilogx will accept.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created plot.
Produce a 2-D plot using a logarithmic scale for the y-axis.
See the documentation of plot for a description of the
arguments that semilogy will accept.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created plot.
Produce a 2-D plot using logarithmic scales for both axes.
See the documentation of plot for a description of the arguments
that loglog will accept.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created plot.
The functions bar, barh, stairs, and stem
are useful for displaying discrete data. For example,
hist (randn (10000, 1), 30); |
produces the histogram of 10,000 normally distributed random numbers shown in fig:hist.
Figure 15.2: Histogram.
Produce a bar graph from two vectors of X-Y data.
If only one argument is given, y, it is taken as a vector of Y values
and the X coordinates are the range 1:numel (y).
The optional input w controls the width of the bars. A value of 1.0 will cause each bar to exactly touch any adjacent bars. The default width is 0.8.
If y is a matrix, then each column of y is taken to be a separate bar graph plotted on the same graph. By default the columns are plotted side-by-side. This behavior can be changed by the style argument which can take the following values:
"grouped" (default) Side-by-side bars with a gap between bars and centered over the X-coordinate.
"stacked"Bars are stacked so that each X value has a single bar composed of multiple segments.
"hist"Side-by-side bars with no gap between bars and centered over the X-coordinate.
"histc"Side-by-side bars with no gap between bars and left-aligned to the X-coordinate.
Optional property/value pairs are passed directly to the underlying patch objects.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a vector of handles to the created "bar series" hggroups with one handle per column of the variable y. This series makes it possible to change a common element in one bar series object and have the change reflected in the other "bar series". For example,
h = bar (rand (5, 10)); set (h(1), "basevalue", 0.5); |
changes the position on the base of all of the bar series.
The following example modifies the face and edge colors using property/value pairs.
bar (randn (1, 100), "facecolor", "r", "edgecolor", "b"); |
The color of the bars is taken from the figure’s colormap, such that
bar (rand (10, 3)); colormap (summer (64)); |
will change the colors used for the bars. The color of bars can also be set
manually using the "facecolor" property as shown below.
h = bar (rand (10, 3)); set (h(1), "facecolor", "r") set (h(2), "facecolor", "g") set (h(3), "facecolor", "b") |
Produce a horizontal bar graph from two vectors of X-Y data.
If only one argument is given, it is taken as a vector of Y values
and the X coordinates are the range 1:numel (y).
The optional input w controls the width of the bars. A value of 1.0 will cause each bar to exactly touch any adjacent bars. The default width is 0.8.
If y is a matrix, then each column of y is taken to be a separate bar graph plotted on the same graph. By default the columns are plotted side-by-side. This behavior can be changed by the style argument which can take the following values:
"grouped" (default) Side-by-side bars with a gap between bars and centered over the Y-coordinate.
"stacked"Bars are stacked so that each Y value has a single bar composed of multiple segments.
"hist"Side-by-side bars with no gap between bars and centered over the Y-coordinate.
"histc"Side-by-side bars with no gap between bars and left-aligned to the Y-coordinate.
Optional property/value pairs are passed directly to the underlying patch objects.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created bar series hggroup. For a description of the use of the bar series, see bar.
Produce histogram counts or plots.
With one vector input argument, y, plot a histogram of the values with 10 bins. The range of the histogram bins is determined by the range of the data. With one matrix input argument, y, plot a histogram where each bin contains a bar per input column.
Given a second vector argument, x, use that as the centers of the bins, with the width of the bins determined from the adjacent values in the vector.
If scalar, the second argument, nbins, defines the number of bins.
If a third argument is provided, the histogram is normalized such that the sum of the bars is equal to norm.
Extreme values are lumped into the first and last bins.
The histogram’s appearance may be modified by specifying property/value pairs. For example the face and edge color may be modified.
hist (randn (1, 100), 25, "facecolor", "r", "edgecolor", "b"); |
The histogram’s colors also depend upon the current colormap.
hist (rand (10, 3)); colormap (summer ()); |
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
With two output arguments, produce the values nn (numbers of elements)
and xx (bin centers) such that bar (xx, nn) will
plot the histogram.
Compute and display a stem and leaf plot of the vector x.
The input x should be a vector of integers. Any non-integer values
will be converted to integer by x = fix (x). By default
each element of x will be plotted with the last digit of the element
as a leaf value and the remaining digits as the stem. For example, 123
will be plotted with the stem ‘12’ and the leaf ‘3’. The second
argument, caption, should be a character array which provides a
description of the data. It is included as a heading for the output.
The optional input stem_sz sets the width of each stem.
The stem width is determined by 10^(stem_sz + 1).
The default stem width is 10.
The output of stemleaf is composed of two parts: a
"Fenced Letter Display," followed by the stem-and-leaf plot itself.
The Fenced Letter Display is described in Exploratory Data Analysis.
Briefly, the entries are as shown:
Fenced Letter Display
#% nx|___________________ nx = numel (x)
M% mi| md | mi median index, md median
H% hi|hl hu| hs hi lower hinge index, hl,hu hinges,
1 |x(1) x(nx)| hs h_spreadx(1), x(nx) first
_______ and last data value.
______|step |_______ step 1.5*h_spread
f|ifl ifh| inner fence, lower and higher
|nfl nfh| no.\ of data points within fences
F|ofl ofh| outer fence, lower and higher
|nFl nFh| no.\ of data points outside outer
fences
|
The stem-and-leaf plot shows on each line the stem value followed by the string made up of the leaf digits. If the stem_sz is not 1 the successive leaf values are separated by ",".
With no return argument, the plot is immediately displayed. If an output argument is provided, the plot is returned as an array of strings.
The leaf digits are not sorted. If sorted leaf values are desired, use
xs = sort (x) before calling stemleaf (xs).
The stem and leaf plot and associated displays are described in: Ch. 3, Exploratory Data Analysis by J. W. Tukey, Addison-Wesley, 1977.
Convert any object acceptable to disp into the format
selected by the suffix of filename. If the return argument
out_file is given, the name of the created file is returned.
This function is intended to facilitate manipulation of the output
of functions such as stemleaf.
See also: stemleaf.
Produce a stairstep plot.
The arguments x and y may be vectors or matrices. If only one argument is given, it is taken as a vector of Y values and the X coordinates are taken to be the indices of the elements.
The style to use for the plot can be defined with a line style style
of the same format as the plot command.
Multiple property/value pairs may be specified, but they must appear in pairs.
If the first argument hax is an axis handle, then plot into this axis,
rather than the current axis handle returned by gca.
If one output argument is requested, return a graphics handle to the created plot. If two output arguments are specified, the data are generated but not plotted. For example,
stairs (x, y); |
and
[xs, ys] = stairs (x, y); plot (xs, ys); |
are equivalent.
Plot a 2-D stem graph.
If only one argument is given, it is taken as the y-values and the x-coordinates are taken from the indices of the elements.
If y is a matrix, then each column of the matrix is plotted as a separate stem graph. In this case x can either be a vector, the same length as the number of rows in y, or it can be a matrix of the same size as y.
The default color is "b" (blue), the default line style is
"-", and the default marker is "o". The line style can
be altered by the linespec argument in the same manner as the
plot command. If the "filled" argument is present the
markers at the top of the stems will be filled in. For example,
x = 1:10; y = 2*x; stem (x, y, "r"); |
plots 10 stems with heights from 2 to 20 in red;
Optional property/value pairs may be specified to control the appearance of the plot.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a handle to a "stem series" hggroup. The single hggroup handle has all of the graphical elements comprising the plot as its children; This allows the properties of multiple graphics objects to be changed by modifying just a single property of the "stem series" hggroup.
For example,
x = [0:10]'; y = [sin(x), cos(x)] h = stem (x, y); set (h(2), "color", "g"); set (h(1), "basevalue", -1) |
changes the color of the second "stem series" and moves the base line of the first.
Stem Series Properties
The linestyle of the stem. (Default: "-")
The width of the stem. (Default: 0.5)
The color of the stem, and if not separately specified, the marker.
(Default: "b" [blue])
The marker symbol to use at the top of each stem. (Default: "o")
The edge color of the marker. (Default: "color" property)
The color to use for "filling" the marker.
(Default: "none" [unfilled])
The size of the marker. (Default: 6)
The handle of the line object which implements the baseline. Use set
with the returned handle to change graphic properties of the baseline.
The y-value where the baseline is drawn. (Default: 0)
Plot a 3-D stem graph.
Stems are drawn from the height z to the location in the x-y plane
determined by x and y. The default color is "b" (blue),
the default line style is "-", and the default marker is "o".
The line style can be altered by the linespec argument in the same
manner as the plot command. If the "filled" argument is
present the markers at the top of the stems will be filled in.
Optional property/value pairs may be specified to control the appearance of the plot.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a handle to the "stem series" hggroup containing the line and marker objects used for the plot. See stem, for a description of the "stem series" object.
Example:
theta = 0:0.2:6; stem3 (cos (theta), sin (theta), theta); |
plots 31 stems with heights from 0 to 6 lying on a circle.
Implementation Note: Color definitions with RGB-triples are not valid.
Draw a 2-D scatter plot.
A marker is plotted at each point defined by the coordinates in the vectors x and y.
The size of the markers is determined by s, which can be a scalar or a vector of the same length as x and y. If s is not given, or is an empty matrix, then a default value of 8 points is used.
The color of the markers is determined by c, which can be a string defining a fixed color; a 3-element vector giving the red, green, and blue components of the color; a vector of the same length as x that gives a scaled index into the current colormap; or an Nx3 matrix defining the RGB color of each marker individually.
The marker to use can be changed with the style argument, that is a
string defining a marker in the same manner as the plot command.
If no marker is specified it defaults to "o" or circles.
If the argument "filled" is given then the markers are filled.
Additional property/value pairs are passed directly to the underlying patch object.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created patch object.
Example:
x = randn (100, 1); y = randn (100, 1); scatter (x, y, [], sqrt (x.^2 + y.^2)); |
Scatter plot of the columns of one matrix against another.
Given the arguments x and y, that have a matching number of
rows, plotmatrix plots a set of axes corresponding to
plot (x(:, i), y(:, j)) |
Given a single argument x this is equivalent to
plotmatrix (x, x) |
except that the diagonal of the set of axes will be replaced with the
histogram hist (x(:, i)).
The marker to use can be changed with the style argument, that is a
string defining a marker in the same manner as the plot command.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h provides handles to the individual
graphics objects in the scatter plots, whereas ax returns the
handles to the scatter plot axis objects. bigax is a hidden
axis object that surrounds the other axes, such that the commands
xlabel, title, etc., will be associated with this hidden
axis. Finally, p returns the graphics objects associated with
the histogram and pax the corresponding axes objects.
Example:
plotmatrix (randn (100, 3), "g+") |
Draw a Pareto chart.
A Pareto chart is a bar graph that arranges information in such a way that priorities for process improvement can be established; It organizes and displays information to show the relative importance of data. The chart is similar to the histogram or bar chart, except that the bars are arranged in decreasing magnitude from left to right along the x-axis.
The fundamental idea (Pareto principle) behind the use of Pareto diagrams is that the majority of an effect is due to a small subset of the causes. For quality improvement, the first few contributing causes (leftmost bars as presented on the diagram) to a problem usually account for the majority of the result. Thus, targeting these "major causes" for elimination results in the most cost-effective improvement scheme.
Typically only the magnitude data y is present in which case
x is taken to be the range 1 : length (y). If x
is given it may be a string array, a cell array of strings, or a numerical
vector.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a 2-element vector with a graphics handle for the created bar plot and a second handle for the created line plot.
An example of the use of pareto is
Cheese = {"Cheddar", "Swiss", "Camembert", ...
"Munster", "Stilton", "Blue"};
Sold = [105, 30, 70, 10, 15, 20];
pareto (Sold, Cheese);
|
Plot an angular histogram.
With one vector argument, th, plot the histogram with 20 angular bins. If th is a matrix then each column of th produces a separate histogram.
If nbins is given and is a scalar, then the histogram is produced with nbin bins. If bins is a vector, then the center of each bin is defined by the values of bins and the number of bins is given by the number of elements in bins.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a vector of graphics handles to the line objects representing each histogram.
If two output arguments are requested then no plot is made and the polar vectors necessary to plot the histogram are returned instead.
[th, r] = rose ([2*randn(1e5,1), pi + 2*randn(1e5,1)]); polar (th, r); |
The contour, contourf and contourc functions
produce two-dimensional contour plots from three-dimensional data.
Create a 2-D contour plot.
Plot level curves (contour lines) of the matrix z, using the
contour matrix c computed by contourc from the same
arguments; see the latter for their interpretation.
The appearance of contour lines can be defined with a line style style
in the same manner as plot. Only line style and color are used;
Any markers defined by style are ignored.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional output c are the contour levels in contourc format.
The optional return value h is a graphics handle to the hggroup comprising the contour lines.
Example:
x = 0:2; y = x; z = x' * y; contour (x, y, z, 2:3) |
See also: ezcontour, contourc, contourf, contour3, clabel, meshc, surfc, caxis, colormap, plot.
Create a 2-D contour plot with filled intervals.
Plot level curves (contour lines) of the matrix z and fill the region between lines with colors from the current colormap.
The level curves are taken from the contour matrix c computed by
contourc for the same arguments; see the latter for their
interpretation.
The appearance of contour lines can be defined with a line style style
in the same manner as plot. Only line style and color are used;
Any markers defined by style are ignored.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional output c are the contour levels in contourc format.
The optional return value h is a graphics handle to the hggroup comprising the contour lines.
The following example plots filled contours of the peaks function.
[x, y, z] = peaks (50); contourf (x, y, z, -7:9) |
See also: ezcontourf, contour, contourc, contour3, clabel, meshc, surfc, caxis, colormap, plot.
Compute contour lines (isolines of constant Z value).
The matrix z contains height values above the rectangular grid
determined by x and y. If only a single input z is
provided then x is taken to be 1:rows (z) and y is
taken to be 1:columns (z).
The optional input vn is either a scalar denoting the number of
contour lines to compute or a vector containing the Z values where lines
will be computed. When vn is a vector the number of contour lines
is numel (vn). However, to compute a single contour line
at a given value use vn = [val, val]. If vn is omitted
it defaults to 10.
The return value c is a 2xn matrix containing the contour lines in the following format
c = [lev1, x1, x2, …, levn, x1, x2, ...
len1, y1, y2, …, lenn, y1, y2, …]
|
in which contour line n has a level (height) of levn and length of lenn.
The optional return value lev is a vector with the Z values of of the contour levels.
Example:
x = 0:2;
y = x;
z = x' * y;
contourc (x, y, z, 2:3)
⇒ 2.0000 2.0000 1.0000 3.0000 1.5000 2.0000
2.0000 1.0000 2.0000 2.0000 2.0000 1.5000
|
Create a 3-D contour plot.
contour3 plots level curves (contour lines) of the matrix z
at a Z level corresponding to each contour. This is in contrast to
contour which plots all of the contour lines at the same Z level
and produces a 2-D plot.
The level curves are taken from the contour matrix c computed by
contourc for the same arguments; see the latter for their
interpretation.
The appearance of contour lines can be defined with a line style style
in the same manner as plot. Only line style and color are used;
Any markers defined by style are ignored.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional output c are the contour levels in contourc format.
The optional return value h is a graphics handle to the hggroup comprising the contour lines.
Example:
contour3 (peaks (19)); colormap cool; hold on; surf (peaks (19), "facecolor", "none", "edgecolor", "black"); |
See also: contour, contourc, contourf, clabel, meshc, surfc, caxis, colormap, plot.
The errorbar, semilogxerr, semilogyerr, and
loglogerr functions produce plots with error bar markers. For
example,
x = 0:0.1:10; y = sin (x); yp = 0.1 .* randn (size (x)); ym = -0.1 .* randn (size (x)); errorbar (x, sin (x), ym, yp); |
produces the figure shown in fig:errorbar.
Figure 15.3: Errorbar plot.
Create a 2-D plot with errorbars.
Many different combinations of arguments are possible. The simplest form is
errorbar (y, ey) |
where the first argument is taken as the set of y coordinates, the
second argument ey are the errors around the y values, and the
x coordinates are taken to be the indices of the elements
(1:numel (y)).
The general form of the function is
errorbar (x, y, err1, …, fmt, …) |
After the x and y arguments there can be 1, 2, or 4 parameters specifying the error values depending on the nature of the error values and the plot format fmt.
When the error is a scalar all points share the same error value. The errorbars are symmetric and are drawn from data-err to data+err. The fmt argument determines whether err is in the x-direction, y-direction (default), or both.
Each data point has a particular error value. The errorbars are symmetric and are drawn from data(n)-err(n) to data(n)+err(n).
The errors have a single low-side value and a single upper-side value. The errorbars are not symmetric and are drawn from data-lerr to data+uerr.
Each data point has a low-side error and an upper-side error. The errorbars are not symmetric and are drawn from data(n)-lerr(n) to data(n)+uerr(n).
Any number of data sets (x1,y1, x2,y2, …) may appear as long as they are separated by a format string fmt.
If y is a matrix, x and the error parameters must also be matrices having the same dimensions. The columns of y are plotted versus the corresponding columns of x and errorbars are taken from the corresponding columns of the error parameters.
If fmt is missing, the yerrorbars ("~") plot style is assumed.
If the fmt argument is supplied then it is interpreted, as in normal plots, to specify the line style, marker, and color. In addition, fmt may include an errorbar style which must precede the ordinary format codes. The following errorbar styles are supported:
Set yerrorbars plot style (default).
Set xerrorbars plot style.
Set xyerrorbars plot style.
Set yboxes plot style.
Set xboxes plot style.
Set xyboxes plot style.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a handle to the hggroup object representing the data plot and errorbars.
Note: For compatibility with MATLAB a line is drawn through all data
points. However, most scientific errorbar plots are a scatter plot of
points with errorbars. To accomplish this, add a marker style to the
fmt argument such as ".". Alternatively, remove the line
by modifying the returned graphic handle with
set (h, "linestyle", "none").
Examples:
errorbar (x, y, ex, ">.r") |
produces an xerrorbar plot of y versus x with x
errorbars drawn from x-ex to x+ex. The marker
"." is used so no connecting line is drawn and the errorbars
appear in red.
errorbar (x, y1, ey, "~",
x, y2, ly, uy)
|
produces yerrorbar plots with y1 and y2 versus x. Errorbars for y1 are drawn from y1-ey to y1+ey, errorbars for y2 from y2-ly to y2+uy.
errorbar (x, y, lx, ux,
ly, uy, "~>")
|
produces an xyerrorbar plot of y versus x in which x errorbars are drawn from x-lx to x+ux and y errorbars from y-ly to y+uy.
See also: semilogxerr, semilogyerr, loglogerr, plot.
Produce 2-D plots using a logarithmic scale for the x-axis and errorbars at each data point.
Many different combinations of arguments are possible. The most common form is
semilogxerr (x, y, ey, fmt) |
which produces a semi-logarithmic plot of y versus x with errors in the y-scale defined by ey and the plot format defined by fmt. See errorbar, for available formats and additional information.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
See also: errorbar, semilogyerr, loglogerr.
Produce 2-D plots using a logarithmic scale for the y-axis and errorbars at each data point.
Many different combinations of arguments are possible. The most common form is
semilogyerr (x, y, ey, fmt) |
which produces a semi-logarithmic plot of y versus x with errors in the y-scale defined by ey and the plot format defined by fmt. See errorbar, for available formats and additional information.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
See also: errorbar, semilogxerr, loglogerr.
Produce 2-D plots on a double logarithm axis with errorbars.
Many different combinations of arguments are possible. The most common form is
loglogerr (x, y, ey, fmt) |
which produces a double logarithm plot of y versus x with errors in the y-scale defined by ey and the plot format defined by fmt. See errorbar, for available formats and additional information.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
See also: errorbar, semilogxerr, semilogyerr.
Finally, the polar function allows you to easily plot data in
polar coordinates. However, the display coordinates remain rectangular
and linear. For example,
polar (0:0.1:10*pi, 0:0.1:10*pi); |
produces the spiral plot shown in fig:polar.
Figure 15.4: Polar plot.
Create a 2-D plot from polar coordinates theta and rho.
If a single complex input cplx is given then the real part is used for theta and the imaginary part is used for rho.
The optional argument fmt specifies the line format in the same way
as plot.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created plot.
Plot a 2-D pie chart.
When called with a single vector argument, produce a pie chart of the
elements in x. The size of the ith slice is the percentage that the
element xi represents of the total sum of x:
pct = x(i) / sum (x).
The optional input explode is a vector of the same length as x that, if non-zero, "explodes" the slice from the pie chart.
The optional input labels is a cell array of strings of the same length as x specifying the label for each slice.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a list of handles to the patch and text objects generating the plot.
Note: If sum (x) ≤ 1 then the elements of x are
interpreted as percentages directly and are not normalized by sum (x).
Furthermore, if the sum is less than 1 then there will be a missing slice
in the pie plot to represent the missing, unspecified percentage.
Plot a 3-D pie chart.
Called with a single vector argument, produces a 3-D pie chart of the
elements in x. The size of the ith slice is the percentage that the
element xi represents of the total sum of x:
pct = x(i) / sum (x).
The optional input explode is a vector of the same length as x that, if non-zero, "explodes" the slice from the pie chart.
The optional input labels is a cell array of strings of the same length as x specifying the label for each slice.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a list of graphics handles to the patch, surface, and text objects generating the plot.
Note: If sum (x) ≤ 1 then the elements of x are
interpreted as percentages directly and are not normalized by sum (x).
Furthermore, if the sum is less than 1 then there will be a missing slice
in the pie plot to represent the missing, unspecified percentage.
Plot the (u, v) components of a vector field in an (x, y) meshgrid. If the grid is uniform, you can specify x and y as vectors.
If x and y are undefined they are assumed to be
(1:m, 1:n) where
[m, n] = size (u).
The variable s is a scalar defining a scaling factor to use for the arrows of the field relative to the mesh spacing. A value of 0 disables all scaling. The default value is 0.9.
The style to use for the plot can be defined with a line style style
of the same format as the plot command.
If a marker is specified then markers at the grid points of the vectors are
drawn rather than arrows. If the argument "filled" is given then
the markers are filled.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to a quiver object. A quiver object regroups the components of the quiver plot (body, arrow, and marker), and allows them to be changed together.
Example:
[x, y] = meshgrid (1:2:20); h = quiver (x, y, sin (2*pi*x/10), sin (2*pi*y/10)); set (h, "maxheadsize", 0.33); |
Plot the (u, v, w) components of a vector field in an (x, y, z) meshgrid. If the grid is uniform, you can specify x, y, and z as vectors.
If x, y, and z are undefined they are assumed to be
(1:m, 1:n, 1:p) where [m, n] =
size (u) and p = max (size (w)).
The variable s is a scalar defining a scaling factor to use for the arrows of the field relative to the mesh spacing. A value of 0 disables all scaling. The default value is 0.9.
The style to use for the plot can be defined with a line style style
of the same format as the plot command.
If a marker is specified then markers at the grid points of the vectors are
drawn rather than arrows. If the argument "filled" is given then the
markers are filled.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to a quiver object. A quiver object regroups the components of the quiver plot (body, arrow, and marker), and allows them to be changed together.
[x, y, z] = peaks (25); surf (x, y, z); hold on; [u, v, w] = surfnorm (x, y, z / 10); h = quiver3 (x, y, z, u, v, w); set (h, "maxheadsize", 0.33); |
Plot the (u, v) components of a vector field emanating
from the origin of a polar plot.
The arrow representing each vector has one end at the origin and the tip at
[u(i), v(i)]. If a single complex argument z is given,
then u = real (z) and v = imag (z).
The style to use for the plot can be defined with a line style style
of the same format as the plot command.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a vector of graphics handles to the line objects representing the drawn vectors.
a = toeplitz ([1;randn(9,1)], [1,randn(1,9)]); compass (eig (a)); |
Plot the (u, v) components of a vector field emanating
from equidistant points on the x-axis.
If a single complex argument z is given, then
u = real (z) and v = imag (z).
The style to use for the plot can be defined with a line style style
of the same format as the plot command.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a vector of graphics handles to the line objects representing the drawn vectors.
phi = [0 : 15 : 360] * pi/180; feather (sin (phi), cos (phi)); |
Produce a 2-D density plot.
A pcolor plot draws rectangles with colors from the matrix c
over the two-dimensional region represented by the matrices x and
y. x and y are the coordinates of the mesh’s vertices
and are typically the output of meshgrid. If x and y are
vectors, then a typical vertex is (x(j), y(i), c(i,j)).
Thus, columns of c correspond to different x values and rows
of c correspond to different y values.
The values in c are scaled to span the range of the current
colormap. Limits may be placed on the color axis by the command
caxis, or by setting the clim property of the parent axis.
The face color of each cell of the mesh is determined by interpolating
the values of c for each of the cell’s vertices; Contrast this with
imagesc which renders one cell for each element of c.
shading modifies an attribute determining the manner by which the
face color of each cell is interpolated from the values of c,
and the visibility of the cells’ edges. By default the attribute is
"faceted", which renders a single color for each cell’s face with
the edge visible.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created surface object.
Area plot of the columns of y.
This plot shows the contributions of each column value to the row sum. It
is functionally similar to plot (x, cumsum (y, 2)),
except that the area under the curve is shaded.
If the x argument is omitted it defaults to 1:rows (y).
A value lvl can be defined that determines where the base level of
the shading under the curve should be defined. The default level is 0.
Additional property/value pairs are passed directly to the underlying patch object.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the hggroup
object comprising the area patch objects. The "BaseValue" property
of the hggroup can be used to adjust the level where shading begins.
Example: Verify identity sin^2 + cos^2 = 1
t = linspace (0, 2*pi, 100)';
y = [sin(t).^2, cos(t).^2)];
area (t, y);
legend ("sin^2", "cos^2", "location", "NorthEastOutside");
|
Produce a simple comet style animation along the trajectory provided by the input coordinate vectors (x, y). If x is not specified it defaults to the indices of y.
The speed of the comet may be controlled by p, which represents the time each point is displayed before moving to the next one. The default for p is 0.1 seconds.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
See also: comet3.
Produce a simple comet style animation along the trajectory provided by the input coordinate vectors (x, y, z). If only z is specified then x, y default to the indices of z.
The speed of the comet may be controlled by p, which represents the time each point is displayed before moving to the next one. The default for p is 0.1 seconds.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
See also: comet.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The axis function may be used to change the axis limits of an existing plot and various other axis properties, such as the aspect ratio and the appearance of tic marks.
Set axis limits and appearance.
The argument limits should be a 2-, 4-, or 6-element vector. The first and second elements specify the lower and upper limits for the x-axis. The third and fourth specify the limits for the y-axis, and the fifth and sixth specify the limits for the z-axis.
Without any arguments, axis turns autoscaling on.
With one output argument, limits = axis returns the current
axis limits.
The vector argument specifying limits is optional, and additional string arguments may be used to specify various axis properties. For example,
axis ([1, 2, 3, 4], "square"); |
forces a square aspect ratio, and
axis ("tic", "labely");
|
turns tic marks on for all axes and tic mark labels on for the y-axis only.
The following options control the aspect ratio of the axes.
"square"Force a square aspect ratio.
"equal"Force x distance to equal y-distance.
"normal"Restore default aspect ratio.
The following options control the way axis limits are interpreted.
"auto"Set the specified axes to have nice limits around the data or all if no axes are specified.
"manual"Fix the current axes limits.
"tight"Fix axes to the limits of the data.
"image"Equivalent to "tight" and "equal".
The following options affect the appearance of tic marks.
"on"Turn tic marks and labels on for all axes.
"off"Turn tic marks off for all axes.
"tic[xyz]"Turn tic marks on for all axes, or turn them on for the specified axes and off for the remainder.
"label[xyz]"Turn tic labels on for all axes, or turn them on for the specified axes and off for the remainder.
"nolabel"Turn tic labels off for all axes.
Note, if there are no tic marks for an axis, there can be no labels.
The following options affect the direction of increasing values on the axes.
"ij"Reverse y-axis, so lower values are nearer the top.
"xy"Restore y-axis, so higher values are nearer the top.
If the first argument hax is an axes handle, then operate on
this axes rather than the current axes returned by gca.
Similarly the axis limits of the colormap can be changed with the caxis function.
Query or set color axis limits for plots.
The limits argument should be a 2-element vector specifying the lower and upper limits to assign to the first and last value in the colormap. Data values outside this range are clamped to the first and last colormap entries.
If the "auto" option is given then automatic colormap limits are
applied. The automatic algorithm sets cmin to the minimum data value
and cmax to the maximum data value. If "manual" is specified
then the "climmode" property is set to "manual" and the
numeric values in the "clim" property are used for limits.
If the first argument hax is an axes handle, then operate on
this axis rather than the current axes returned by gca.
Called without arguments the current color axis limits are returned.
See also: colormap.
The xlim, ylim, and zlim functions may be used to
get or set individual axis limits. Each has the same form.
Query or set the limits of the x-axis for the current plot.
Called without arguments xlim returns the x-axis limits of the
current plot. With the input query "mode", return the current
x-limit calculation mode which is either "auto" or "manual".
If passed a 2-element vector [x_lo x_hi], the limits of the
x-axis are set to these values and the mode is set to "manual".
The current plotting mode can be changed by using either "auto"
or "manual" as the argument.
If the first argument hax is an axes handle, then operate on
this axis rather than the current axes returned by gca.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave can plot a function from a function handle, inline function, or
string defining the function without the user needing to explicitly
create the data to be plotted. The function fplot also generates
two-dimensional plots with linear axes using a function name and limits
for the range of the x-coordinate instead of the x and y data. For
example,
fplot (@sin, [-10, 10], 201); |
produces a plot that is equivalent to the one above, but also includes a legend displaying the name of the plotted function.
Plot a function fn within the range defined by limits.
fn is a function handle, inline function, or string containing the name of the function to evaluate.
The limits of the plot are of the form [xlo, xhi] or
[xlo, xhi, ylo, yhi].
The next three arguments are all optional and any number of them may be given in any order.
tol is the relative tolerance to use for the plot and defaults to 2e-3 (.2%).
n is the minimum number of points to use. When n is specified,
the maximum stepsize will be xhi - xlo / n. More
than n points may still be used in order to meet the relative
tolerance requirement.
The fmt argument specifies the linestyle to be used by the plot command.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
With no output arguments the results are immediately plotted. With two
output arguments the 2-D plot data is returned. The data can subsequently
be plotted manually with plot (x, y).
Example:
fplot (@cos, [0, 2*pi])
fplot ("[cos(x), sin(x)]", [0, 2*pi])
|
Note: fplot works best with continuous functions. Functions with
discontinuities are unlikely to plot well. This restriction may be removed
in the future.
Other functions that can create two-dimensional plots directly from a
function include ezplot, ezcontour, ezcontourf and
ezpolar.
Plot the 2-D curve defined by the function f.
The function f may be a string, inline function, or function handle
and can have either one or two variables. If f has one variable, then
the function is plotted over the domain -2*pi < x < 2*pi
with 500 points.
If f2v is a function of two variables then the implicit function
f(x,y) = 0 is calculated over the meshed domain
-2*pi <= x | y <= 2*pi with 60 points in each dimension.
For example:
ezplot (@(x, y) x.^2 - y.^2 - 1) |
If two functions are passed as inputs then the parametric function
x = fx (t) y = fy (t) |
is plotted over the domain -2*pi <= t <= 2*pi with 500 points.
If dom is a two element vector, it represents the minimum and maximum
values of both x and y, or t for a parametric plot. If
dom is a four element vector, then the minimum and maximum values are
[xmin xmax ymin ymax].
n is a scalar defining the number of points to use in plotting the function.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a vector of graphics handles to the created line objects.
See also: plot, ezplot3, ezpolar, ezcontour, ezcontourf, ezmesh, ezmeshc, ezsurf, ezsurfc.
Plot the contour lines of a function.
f is a string, inline function, or function handle with two arguments
defining the function. By default the plot is over the meshed domain
-2*pi <= x | y <= 2*pi with 60 points in each dimension.
If dom is a two element vector, it represents the minimum and maximum
values of both x and y. If dom is a four element vector,
then the minimum and maximum values are [xmin xmax ymin ymax].
n is a scalar defining the number of points to use in each dimension.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created plot.
Example:
f = @(x,y) sqrt (abs (x .* y)) ./ (1 + x.^2 + y.^2); ezcontour (f, [-3, 3]); |
See also: contour, ezcontourf, ezplot, ezmeshc, ezsurfc.
Plot the filled contour lines of a function.
f is a string, inline function, or function handle with two arguments
defining the function. By default the plot is over the meshed domain
-2*pi <= x | y <= 2*pi with 60 points in each dimension.
If dom is a two element vector, it represents the minimum and maximum
values of both x and y. If dom is a four element vector,
then the minimum and maximum values are [xmin xmax ymin ymax].
n is a scalar defining the number of points to use in each dimension.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created plot.
Example:
f = @(x,y) sqrt (abs (x .* y)) ./ (1 + x.^2 + y.^2); ezcontourf (f, [-3, 3]); |
Plot a 2-D function in polar coordinates.
The function f is a string, inline function, or function handle with
a single argument. The expected form of the function is
rho = f(theta).
By default the plot is over the domain 0 <= theta <= 2*pi
with 500 points.
If dom is a two element vector, it represents the minimum and maximum values of theta.
n is a scalar defining the number of points to use in plotting the function.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created plot.
Example:
ezpolar (@(t) sin (5/4 * t), [0, 8*pi]); |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Draw a rectangular patch defined by pos and curv.
The variable pos(1:2) defines the lower left-hand corner of
the patch and pos(3:4) defines its width and height. By
default, the value of pos is [0, 0, 1, 1].
The variable curv defines the curvature of the sides of the rectangle and may be a scalar or two-element vector with values between 0 and 1. A value of 0 represents no curvature of the side, whereas a value of 1 means that the side is entirely curved into the arc of a circle. If curv is a two-element vector, then the first element is the curvature along the x-axis of the patch and the second along y-axis.
If curv is a scalar, it represents the curvature of the shorter of the two sides of the rectangle and the curvature of the other side is defined by
min (pos(1:2)) / max (pos(1:2)) * curv |
Additional property/value pairs are passed to the underlying patch command.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created rectangle object.
See also: patch, line, cylinder, ellipsoid, sphere.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The function mesh produces mesh surface plots. For example,
tx = ty = linspace (-8, 8, 41)'; [xx, yy] = meshgrid (tx, ty); r = sqrt (xx .^ 2 + yy .^ 2) + eps; tz = sin (r) ./ r; mesh (tx, ty, tz); |
produces the familiar “sombrero” plot shown in fig:mesh. Note
the use of the function meshgrid to create matrices of X and Y
coordinates to use for plotting the Z data. The ndgrid function
is similar to meshgrid, but works for N-dimensional matrices.
Figure 15.5: Mesh plot.
The meshc function is similar to mesh, but also produces a
plot of contours for the surface.
The plot3 function displays arbitrary three-dimensional data,
without requiring it to form a surface. For example,
t = 0:0.1:10*pi; r = linspace (0, 1, numel (t)); z = linspace (0, 1, numel (t)); plot3 (r.*sin(t), r.*cos(t), z); |
displays the spiral in three dimensions shown in fig:plot3.
Figure 15.6: Three-dimensional spiral.
Finally, the view function changes the viewpoint for
three-dimensional plots.
Plot a 3-D wireframe mesh.
The wireframe mesh is plotted using rectangles. The vertices of the
rectangles [x, y] are typically the output of meshgrid.
over a 2-D rectangular region in the x-y plane. z determines the
height above the plane of each vertex. If only a single z matrix is
given, then it is plotted over the meshgrid
x = 1:columns (z), y = 1:rows (z).
Thus, columns of z correspond to different x values and rows
of z correspond to different y values.
The color of the mesh is computed by linearly scaling the z values
to fit the range of the current colormap. Use caxis and/or
change the colormap to control the appearance.
Optionally, the color of the mesh can be specified independently of z by supplying a color matrix, c.
Any property/value pairs are passed directly to the underlying surface object.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created surface object.
See also: ezmesh, meshc, meshz, trimesh, contour, surf, surface, meshgrid, hidden, shading, colormap, caxis.
Plot a 3-D wireframe mesh with underlying contour lines.
The wireframe mesh is plotted using rectangles. The vertices of the
rectangles [x, y] are typically the output of meshgrid.
over a 2-D rectangular region in the x-y plane. z determines the
height above the plane of each vertex. If only a single z matrix is
given, then it is plotted over the meshgrid
x = 1:columns (z), y = 1:rows (z).
Thus, columns of z correspond to different x values and rows
of z correspond to different y values.
The color of the mesh is computed by linearly scaling the z values
to fit the range of the current colormap. Use caxis and/or
change the colormap to control the appearance.
Optionally the color of the mesh can be specified independently of z by supplying a color matrix, c.
Any property/value pairs are passed directly to the underlying surface object.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a 2-element vector with a graphics handle to the created surface object and to the created contour plot.
See also: ezmeshc, mesh, meshz, contour, surfc, surface, meshgrid, hidden, shading, colormap, caxis.
Plot a 3-D wireframe mesh with a surrounding curtain.
The wireframe mesh is plotted using rectangles. The vertices of the
rectangles [x, y] are typically the output of meshgrid.
over a 2-D rectangular region in the x-y plane. z determines the
height above the plane of each vertex. If only a single z matrix is
given, then it is plotted over the meshgrid
x = 1:columns (z), y = 1:rows (z).
Thus, columns of z correspond to different x values and rows
of z correspond to different y values.
The color of the mesh is computed by linearly scaling the z values
to fit the range of the current colormap. Use caxis and/or
change the colormap to control the appearance.
Optionally the color of the mesh can be specified independently of z by supplying a color matrix, c.
Any property/value pairs are passed directly to the underlying surface object.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created surface object.
See also: mesh, meshc, contour, surf, surface, waterfall, meshgrid, hidden, shading, colormap, caxis.
Control mesh hidden line removal.
When called with no argument the hidden line removal state is toggled.
When called with one of the modes "on" or "off" the state
is set accordingly.
The optional output argument mode is the current state.
Hidden Line Removal determines what graphic objects behind a mesh plot are visible. The default is for the mesh to be opaque and lines behind the mesh are not visible. If hidden line removal is turned off then objects behind the mesh can be seen through the faces (openings) of the mesh, although the mesh grid lines are still opaque.
See also: mesh, meshc, meshz, ezmesh, ezmeshc, trimesh, waterfall.
Plot a 3-D surface mesh.
The surface mesh is plotted using shaded rectangles. The vertices of the
rectangles [x, y] are typically the output of meshgrid.
over a 2-D rectangular region in the x-y plane. z determines the
height above the plane of each vertex. If only a single z matrix is
given, then it is plotted over the meshgrid
x = 1:columns (z), y = 1:rows (z).
Thus, columns of z correspond to different x values and rows
of z correspond to different y values.
The color of the surface is computed by linearly scaling the z values
to fit the range of the current colormap. Use caxis and/or
change the colormap to control the appearance.
Optionally, the color of the surface can be specified independently of z by supplying a color matrix, c.
Any property/value pairs are passed directly to the underlying surface object.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created surface object.
Note: The exact appearance of the surface can be controlled with the
shading command or by using set to control surface object
properties.
See also: ezsurf, surfc, surfl, surfnorm, trisurf, contour, mesh, surface, meshgrid, hidden, shading, colormap, caxis.
Plot a 3-D surface mesh with underlying contour lines.
The surface mesh is plotted using shaded rectangles. The vertices of the
rectangles [x, y] are typically the output of meshgrid.
over a 2-D rectangular region in the x-y plane. z determines the
height above the plane of each vertex. If only a single z matrix is
given, then it is plotted over the meshgrid
x = 1:columns (z), y = 1:rows (z).
Thus, columns of z correspond to different x values and rows
of z correspond to different y values.
The color of the surface is computed by linearly scaling the z values
to fit the range of the current colormap. Use caxis and/or
change the colormap to control the appearance.
Optionally, the color of the surface can be specified independently of z by supplying a color matrix, c.
Any property/value pairs are passed directly to the underlying surface object.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created surface object.
Note: The exact appearance of the surface can be controlled with the
shading command or by using set to control surface object
properties.
See also: ezsurfc, surf, surfl, surfnorm, trisurf, contour, mesh, surface, meshgrid, hidden, shading, colormap, caxis.
Plot a 3-D surface using shading based on various lighting models.
The surface mesh is plotted using shaded rectangles. The vertices of the
rectangles [x, y] are typically the output of meshgrid.
over a 2-D rectangular region in the x-y plane. z determines the
height above the plane of each vertex. If only a single z matrix is
given, then it is plotted over the meshgrid
x = 1:columns (z), y = 1:rows (z).
Thus, columns of z correspond to different x values and rows
of z correspond to different y values.
The default lighting mode "cdata", changes the cdata property of the
surface object to give the impression of a lighted surface.
Warning: The alternative mode "light" mode which creates a
light object to illuminate the surface is not implemented (yet).
The light source location can be specified using lsrc. It can be given as a 2-element vector [azimuth, elevation] in degrees, or as a 3-element vector [lx, ly, lz]. The default value is rotated 45 degrees counterclockwise to the current view.
The material properties of the surface can specified using a 4-element vector P = [AM D SP exp] which defaults to p = [0.55 0.6 0.4 10].
"AM" strength of ambient light"D" strength of diffuse reflection"SP" strength of specular reflection"EXP" specular exponentIf the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created surface object.
Example:
colormap (bone (64)); surfl (peaks); shading interp; |
See also: diffuse, specular, surf, shading, colormap, caxis.
Find the vectors normal to a meshgridded surface. The meshed gridded surface is defined by x, y, and z. If x and y are not defined, then it is assumed that they are given by
[x, y] = meshgrid (1:rows (z),
1:columns (z));
|
If no return arguments are requested, a surface plot with the normal vectors to the surface is plotted. Otherwise the components of the normal vectors at the mesh gridded points are returned in nx, ny, and nz.
The normal vectors are calculated by taking the cross product of the diagonals of each of the quadrilaterals in the meshgrid to find the normal vectors of the centers of these quadrilaterals. The four nearest normal vectors to the meshgrid points are then averaged to obtain the normal to the surface at the meshgridded points.
An example of the use of surfnorm is
surfnorm (peaks (25)); |
If called with one output argument and the first input argument
val is a three-dimensional array that contains the data of an
isosurface geometry and the second input argument iso keeps the
isovalue as a scalar value then return a structure array fv
that contains the fields Faces and Vertices at computed
points [x, y, z] = meshgrid (1:l, 1:m, 1:n). The output
argument fv can directly be taken as an input argument for the
patch function.
If called with further input arguments x, y and z which are three–dimensional arrays with the same size than val then the volume data is taken at those given points.
The string input argument "noshare" is only for compatibility and
has no effect. If given the string input argument
"verbose" then print messages to the command line interface about the
current progress.
If called with the input argument col which is a three-dimensional array of the same size than val then take those values for the interpolation of coloring the isosurface geometry. Add the field FaceVertexCData to the structure array fv.
If called with two or three output arguments then return the information about the faces f, vertices v and color data c as separate arrays instead of a single structure array.
If called with no output argument then directly process the
isosurface geometry with the patch command.
For example,
[x, y, z] = meshgrid (1:5, 1:5, 1:5); val = rand (5, 5, 5); isosurface (x, y, z, val, .5); |
will directly draw a random isosurface geometry in a graphics window. Another example for an isosurface geometry with different additional coloring
N = 15; # Increase number of vertices in each direction
iso = .4; # Change isovalue to .1 to display a sphere
lin = linspace (0, 2, N);
[x, y, z] = meshgrid (lin, lin, lin);
c = abs ((x-.5).^2 + (y-.5).^2 + (z-.5).^2);
figure (); # Open another figure window
subplot (2,2,1); view (-38, 20);
[f, v] = isosurface (x, y, z, c, iso);
p = patch ("Faces", f, "Vertices", v, "EdgeColor", "none");
set (gca, "PlotBoxAspectRatioMode", "manual", ...
"PlotBoxAspectRatio", [1 1 1]);
# set (p, "FaceColor", "green", "FaceLighting", "phong");
# light ("Position", [1 1 5]); # Available with the JHandles package
subplot (2,2,2); view (-38, 20);
p = patch ("Faces", f, "Vertices", v, "EdgeColor", "blue");
set (gca, "PlotBoxAspectRatioMode", "manual", ...
"PlotBoxAspectRatio", [1 1 1]);
# set (p, "FaceColor", "none", "FaceLighting", "phong");
# light ("Position", [1 1 5]);
subplot (2,2,3); view (-38, 20);
[f, v, c] = isosurface (x, y, z, c, iso, y);
p = patch ("Faces", f, "Vertices", v, "FaceVertexCData", c, ...
"FaceColor", "interp", "EdgeColor", "none");
set (gca, "PlotBoxAspectRatioMode", "manual", ...
"PlotBoxAspectRatio", [1 1 1]);
# set (p, "FaceLighting", "phong");
# light ("Position", [1 1 5]);
subplot (2,2,4); view (-38, 20);
p = patch ("Faces", f, "Vertices", v, "FaceVertexCData", c, ...
"FaceColor", "interp", "EdgeColor", "blue");
set (gca, "PlotBoxAspectRatioMode", "manual", ...
"PlotBoxAspectRatio", [1 1 1]);
# set (p, "FaceLighting", "phong");
# light ("Position", [1 1 5]);
|
See also: isonormals, isocolors.
If called with one output argument and the first input argument
val is a three-dimensional array that contains the data for an
isosurface geometry and the second input argument v keeps the
vertices of an isosurface then return the normals n in form of
a matrix with the same size than v at computed points
[x, y, z] = meshgrid (1:l, 1:m, 1:n). The output argument
n can be taken to manually set VertexNormals of a patch.
If called with further input arguments x, y and z which are three–dimensional arrays with the same size than val then the volume data is taken at those given points. Instead of the vertices data v a patch handle p can be passed to this function.
If given the string input argument "negate" as last input argument
then compute the reverse vector normals of an isosurface geometry.
If no output argument is given then directly redraw the patch that is given by the patch handle p.
For example:
function [] = isofinish (p)
set (gca, "PlotBoxAspectRatioMode", "manual", ...
"PlotBoxAspectRatio", [1 1 1]);
set (p, "VertexNormals", -get (p,"VertexNormals")); # Revert normals
set (p, "FaceColor", "interp");
## set (p, "FaceLighting", "phong");
## light ("Position", [1 1 5]); # Available with JHandles
endfunction
N = 15; # Increase number of vertices in each direction
iso = .4; # Change isovalue to .1 to display a sphere
lin = linspace (0, 2, N);
[x, y, z] = meshgrid (lin, lin, lin);
c = abs ((x-.5).^2 + (y-.5).^2 + (z-.5).^2);
figure (); # Open another figure window
subplot (2,2,1); view (-38, 20);
[f, v, cdat] = isosurface (x, y, z, c, iso, y);
p = patch ("Faces", f, "Vertices", v, "FaceVertexCData", cdat, ...
"FaceColor", "interp", "EdgeColor", "none");
isofinish (p); ## Call user function isofinish
subplot (2,2,2); view (-38, 20);
p = patch ("Faces", f, "Vertices", v, "FaceVertexCData", cdat, ...
"FaceColor", "interp", "EdgeColor", "none");
isonormals (x, y, z, c, p); # Directly modify patch
isofinish (p);
subplot (2,2,3); view (-38, 20);
p = patch ("Faces", f, "Vertices", v, "FaceVertexCData", cdat, ...
"FaceColor", "interp", "EdgeColor", "none");
n = isonormals (x, y, z, c, v); # Compute normals of isosurface
set (p, "VertexNormals", n); # Manually set vertex normals
isofinish (p);
subplot (2,2,4); view (-38, 20);
p = patch ("Faces", f, "Vertices", v, "FaceVertexCData", cdat, ...
"FaceColor", "interp", "EdgeColor", "none");
isonormals (x, y, z, c, v, "negate"); # Use reverse directly
isofinish (p);
|
See also: isosurface, isocolors.
If called with one output argument and the first input argument
c is a three-dimensional array that contains color values and
the second input argument v keeps the vertices of a geometry
then return a matrix cd with color data information for the
geometry at computed points
[x, y, z] = meshgrid (1:l, 1:m, 1:n). The output argument
cd can be taken to manually set FaceVertexCData of a patch.
If called with further input arguments x, y and z
which are three–dimensional arrays of the same size than c
then the color data is taken at those given points. Instead of the
color data c this function can also be called with RGB values
r, g, b. If input argumnets x, y,
z are not given then again meshgrid computed values
are taken.
Optionally, the patch handle p can be given as the last input argument to all variations of function calls instead of the vertices data v. Finally, if no output argument is given then directly change the colors of a patch that is given by the patch handle p.
For example:
function [] = isofinish (p)
set (gca, "PlotBoxAspectRatioMode", "manual", ...
"PlotBoxAspectRatio", [1 1 1]);
set (p, "FaceColor", "interp");
## set (p, "FaceLighting", "flat");
## light ("Position", [1 1 5]); ## Available with JHandles
endfunction
N = 15; # Increase number of vertices in each direction
iso = .4; # Change isovalue to .1 to display a sphere
lin = linspace (0, 2, N);
[x, y, z] = meshgrid (lin, lin, lin);
c = abs ((x-.5).^2 + (y-.5).^2 + (z-.5).^2);
figure (); # Open another figure window
subplot (2,2,1); view (-38, 20);
[f, v] = isosurface (x, y, z, c, iso);
p = patch ("Faces", f, "Vertices", v, "EdgeColor", "none");
cdat = rand (size (c)); # Compute random patch color data
isocolors (x, y, z, cdat, p); # Directly set colors of patch
isofinish (p); # Call user function isofinish
subplot (2,2,2); view (-38, 20);
p = patch ("Faces", f, "Vertices", v, "EdgeColor", "none");
[r, g, b] = meshgrid (lin, 2-lin, 2-lin);
cdat = isocolors (x, y, z, c, v); # Compute color data vertices
set (p, "FaceVertexCData", cdat); # Set color data manually
isofinish (p);
subplot (2,2,3); view (-38, 20);
p = patch ("Faces", f, "Vertices", v, "EdgeColor", "none");
cdat = isocolors (r, g, b, c, p); # Compute color data patch
set (p, "FaceVertexCData", cdat); # Set color data manually
isofinish (p);
subplot (2,2,4); view (-38, 20);
p = patch ("Faces", f, "Vertices", v, "EdgeColor", "none");
r = g = b = repmat ([1:N] / N, [N, 1, N]); # Black to white
cdat = isocolors (x, y, z, r, g, b, v);
set (p, "FaceVertexCData", cdat);
isofinish (p);
|
See also: isosurface, isonormals.
Reduce the faces area for a given patch, structure or explicit faces
and points matrices by a scale factor sf. The structure
fv must contain the fields "faces" and "vertices".
If the factor sf is omitted then a default of 0.3 is used.
Given a patch handle as the first input argument and no output parameters, perform the shrinking of the patch faces in place and redraw the patch.
If called with one output argument, return a structure with fields
"faces", "vertices", and "facevertexcdata"
containing the data after shrinking which can then directly be used as an
input argument for the patch function.
Performing the shrinking on faces which are not convex can lead to undesired results.
For example,
[phi r] = meshgrid (linspace (0, 1.5*pi, 16), linspace (1, 2, 4));
tri = delaunay (phi(:), r(:));
v = [r(:).*sin(phi(:)) r(:).*cos(phi(:))];
clf ()
p = patch ("Faces", tri, "Vertices", v, "FaceColor", "none");
fv = shrinkfaces (p);
patch (fv)
axis equal
grid on
|
draws a triangulated 3/4 circle and the corresponding shrunken version.
See also: patch.
Calculate diffuse reflection strength of a surface defined by the normal vector elements sx, sy, sz.
The light source location vector lv can be given as 2-element vector [azimuth, elevation] in degrees or as 3-element vector [lx, ly, lz].
Calculate specular reflection strength of a surface defined by the normal vector elements sx, sy, sz using Phong’s approximation.
The light source location and viewer location vectors can be specified using parameter lv and vv respectively. The location vectors can given as 2-element vectors [azimuth, elevation] in degrees or as 3-element vectors [x, y, z].
An optional sixth argument describes the specular exponent (spread) se.
Given vectors of x and y coordinates, return matrices xx and yy corresponding to a full 2-D grid.
The rows of xx are copies of x, and the columns of yy are copies of y. If y is omitted, then it is assumed to be the same as x.
If the optional z input is given, or zz is requested, then the output will be a full 3-D grid.
meshgrid is most frequently used to produce input for a 2-D or 3-D
function that will be plotted. The following example creates a surface
plot of the “sombrero” function.
f = @(x,y) sin (sqrt (x.^2 + y.^2)) ./ sqrt (x.^2 + y.^2); range = linspace (-8, 8, 41); [X, Y] = meshgrid (range, range); Z = f (X, Y); surf (X, Y, Z); |
Programming Note: meshgrid is restricted to 2-D or 3-D grid
generation. The ndgrid function will generate 1-D through N-D
grids. However, the functions are not completely equivalent. If x
is a vector of length M and y is a vector of length N, then
meshgrid will produce an output grid which is NxM. ndgrid
will produce an output which is MxN (transpose) for the same
input. Some core functions expect meshgrid input and others expect
ndgrid input. Check the documentation for the function in question
to determine the proper input format.
Given n vectors x1, …, xn, ndgrid returns
n arrays of dimension n. The elements of the i-th output argument
contains the elements of the vector xi repeated over all
dimensions different from the i-th dimension. Calling ndgrid with
only one input argument x is equivalent to calling ndgrid with
all n input arguments equal to x:
[y1, y2, …, yn] = ndgrid (x, …, x)
Programming Note: ndgrid is very similar to the function
meshgrid except that the first two dimensions are transposed in
comparison to meshgrid. Some core functions expect meshgrid
input and others expect ndgrid input. Check the documentation for
the function in question to determine the proper input format.
See also: meshgrid.
Produce 3-D plots.
Many different combinations of arguments are possible. The simplest form is
plot3 (x, y, z) |
in which the arguments are taken to be the vertices of the points to be plotted in three dimensions. If all arguments are vectors of the same length, then a single continuous line is drawn. If all arguments are matrices, then each column of is treated as a separate line. No attempt is made to transpose the arguments to make the number of rows match.
If only two arguments are given, as
plot3 (x, cplx) |
the real and imaginary parts of the second argument are used as the y and z coordinates, respectively.
If only one argument is given, as
plot3 (cplx) |
the real and imaginary parts of the argument are used as the y and z values, and they are plotted versus their index.
Arguments may also be given in groups of three as
plot3 (x1, y1, z1, x2, y2, z2, …) |
in which each set of three arguments is treated as a separate line or set of lines in three dimensions.
To plot multiple one- or two-argument groups, separate each group with an empty format string, as
plot3 (x1, c1, "", c2, "", …) |
Multiple property-value pairs may be specified which will affect the line
objects drawn by plot3. If the fmt argument is supplied it
will format the line objects in the same manner as plot.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created plot.
Example:
z = [0:0.05:5]; plot3 (cos (2*pi*z), sin (2*pi*z), z, ";helix;"); plot3 (z, exp (2i*pi*z), ";complex sinusoid;"); |
Query or set the viewpoint for the current axes.
The parameters azimuth and elevation can be given as two arguments or as 2-element vector. The viewpoint can also be specified with Cartesian coordinates x, y, and z.
The call view (2) sets the viewpoint to azimuth = 0
and elevation = 90, which is the default for 2-D graphs.
The call view (3) sets the viewpoint to azimuth = -37.5
and elevation = 30, which is the default for 3-D graphs.
If the first argument hax is an axes handle, then operate on
this axis rather than the current axes returned by gca.
If no inputs are given, return the current azimuth and elevation.
Plot slices of 3-D data/scalar fields.
Each element of the 3-dimensional array v represents a scalar value at
a location given by the parameters x, y, and z. The
parameters x, x, and z are either 3-dimensional arrays of
the same size as the array v in the "meshgrid" format or
vectors. The parameters xi, etc. respect a similar format to
x, etc., and they represent the points at which the array vi
is interpolated using interp3. The vectors sx, sy, and
sz contain points of orthogonal slices of the respective axes.
If x, y, z are omitted, they are assumed to be
x = 1:size (v, 2), y = 1:size (v, 1) and
z = 1:size (v, 3).
method is one of:
"nearest"Return the nearest neighbor.
"linear"Linear interpolation from nearest neighbors.
"cubic"Cubic interpolation from four nearest neighbors (not implemented yet).
"spline"Cubic spline interpolation—smooth first and second derivatives throughout the curve.
The default method is "linear".
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created surface object.
Examples:
[x, y, z] = meshgrid (linspace (-8, 8, 32)); v = sin (sqrt (x.^2 + y.^2 + z.^2)) ./ (sqrt (x.^2 + y.^2 + z.^2)); slice (x, y, z, v, [], 0, []); [xi, yi] = meshgrid (linspace (-7, 7)); zi = xi + yi; slice (x, y, z, v, xi, yi, zi); |
Plot a ribbon plot for the columns of y vs. x.
The optional parameter width specifies the width of a single ribbon
(default is 0.75). If x is omitted, a vector containing the
row numbers is assumed (1:rows (Y)).
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a vector of graphics handles to the surface objects representing each ribbon.
Set the shading of patch or surface graphic objects.
Valid arguments for type are
"flat"Single colored patches with invisible edges.
"faceted"Single colored patches with visible edges.
"interp"Color between patch vertices are interpolated and the patch edges are invisible.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
Draw a 3-D scatter plot.
A marker is plotted at each point defined by the coordinates in the vectors x, y, and z.
The size of the markers is determined by s, which can be a scalar or a vector of the same length as x, y, and z. If s is not given, or is an empty matrix, then a default value of 8 points is used.
The color of the markers is determined by c, which can be a string defining a fixed color; a 3-element vector giving the red, green, and blue components of the color; a vector of the same length as x that gives a scaled index into the current colormap; or an Nx3 matrix defining the RGB color of each marker individually.
The marker to use can be changed with the style argument, that is a
string defining a marker in the same manner as the plot command.
If no marker is specified it defaults to "o" or circles.
If the argument "filled" is given then the markers are filled.
Additional property/value pairs are passed directly to the underlying patch object.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the hggroup object representing the points.
[x, y, z] = peaks (20); scatter3 (x(:), y(:), z(:), [], z(:)); |
Plot a 3-D waterfall plot.
A waterfall plot is similar to a meshz plot except only
mesh lines for the rows of z (x-values) are shown.
The wireframe mesh is plotted using rectangles. The vertices of the
rectangles [x, y] are typically the output of meshgrid.
over a 2-D rectangular region in the x-y plane. z determines the
height above the plane of each vertex. If only a single z matrix is
given, then it is plotted over the meshgrid
x = 1:columns (z), y = 1:rows (z).
Thus, columns of z correspond to different x values and rows
of z correspond to different y values.
The color of the mesh is computed by linearly scaling the z values
to fit the range of the current colormap. Use caxis and/or
change the colormap to control the appearance.
Optionally the color of the mesh can be specified independently of z by supplying a color matrix, c.
Any property/value pairs are passed directly to the underlying surface object.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created surface object.
See also: meshz, mesh, meshc, contour, surf, surface, ribbon, meshgrid, hidden, shading, colormap, caxis.
| 15.2.2.1 Aspect Ratio | ||
| 15.2.2.2 Three-dimensional Function Plotting | ||
| 15.2.2.3 Three-dimensional Geometric Shapes |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
For three-dimensional plots the aspect ratio can be set for data with
daspect and for the plot box with pbaspect.
See section Axis Configuration, for controlling the x-, y-, and z-limits for
plotting.
Query or set the data aspect ratio of the current axes.
The aspect ratio is a normalized 3-element vector representing the span of the x, y, and z-axis limits.
daspect (mode)
Set the data aspect ratio mode of the current axes. mode is
either "auto" or "manual".
daspect (
"mode")
Return the data aspect ratio mode of the current axes.
daspect (hax, …)
Operate on the axes in handle hax instead of the current axes.
Query or set the plot box aspect ratio of the current axes.
The aspect ratio is a normalized 3-element vector representing the rendered lengths of the x, y, and z axes.
pbaspect(mode)
Set the plot box aspect ratio mode of the current axes. mode is
either "auto" or "manual".
pbaspect ("mode")
Return the plot box aspect ratio mode of the current axes.
pbaspect (hax, …)
Operate on the axes in handle hax instead of the current axes.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Plot a parametrically defined curve in three dimensions.
fx, fy, and fz are strings, inline functions,
or function handles with one argument defining the function. By
default the plot is over the domain 0 <= t <= 2*pi
with 500 points.
If dom is a two element vector, it represents the minimum and maximum values of t.
n is a scalar defining the number of points to use in plotting the function.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created plot.
fx = @(t) cos (t); fy = @(t) sin (t); fz = @(t) t; ezplot3 (fx, fy, fz, [0, 10*pi], 100); |
Plot the mesh defined by a function.
f is a string, inline function, or function handle with two arguments
defining the function. By default the plot is over the meshed domain
-2*pi <= x | y <= 2*pi with 60 points in each dimension.
If three functions are passed, then plot the parametrically defined
function [fx (s, t), fy (s, t),
fz (s, t)].
If dom is a two element vector, it represents the minimum and maximum
values of both x and y. If dom is a four element vector,
then the minimum and maximum values are [xmin xmax ymin ymax].
n is a scalar defining the number of points to use in each dimension.
If the argument "circ" is given, then the function is plotted over
a disk centered on the middle of the domain dom.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created surface object.
Example 1: 2-argument function
f = @(x,y) sqrt (abs (x .* y)) ./ (1 + x.^2 + y.^2); ezmesh (f, [-3, 3]); |
Example 2: parametrically defined function
fx = @(s,t) cos (s) .* cos (t); fy = @(s,t) sin (s) .* cos (t); fz = @(s,t) sin (t); ezmesh (fx, fy, fz, [-pi, pi, -pi/2, pi/2], 20); |
Plot the mesh and contour lines defined by a function.
f is a string, inline function, or function handle with two arguments
defining the function. By default the plot is over the meshed domain
-2*pi <= x | y <= 2*pi with 60 points in each dimension.
If three functions are passed, then plot the parametrically defined
function [fx (s, t), fy (s, t),
fz (s, t)].
If dom is a two element vector, it represents the minimum and maximum
values of both x and y. If dom is a four element vector,
then the minimum and maximum values are [xmin xmax ymin ymax].
n is a scalar defining the number of points to use in each dimension.
If the argument "circ" is given, then the function is plotted over
a disk centered on the middle of the domain dom.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a 2-element vector with a graphics handle for the created mesh plot and a second handle for the created contour plot.
Example: 2-argument function
f = @(x,y) sqrt (abs (x .* y)) ./ (1 + x.^2 + y.^2); ezmeshc (f, [-3, 3]); |
Plot the surface defined by a function.
f is a string, inline function, or function handle with two arguments
defining the function. By default the plot is over the meshed domain
-2*pi <= x | y <= 2*pi with 60 points in each dimension.
If three functions are passed, then plot the parametrically defined
function [fx (s, t), fy (s, t),
fz (s, t)].
If dom is a two element vector, it represents the minimum and maximum
values of both x and y. If dom is a four element vector,
then the minimum and maximum values are [xmin xmax ymin ymax].
n is a scalar defining the number of points to use in each dimension.
If the argument "circ" is given, then the function is plotted over
a disk centered on the middle of the domain dom.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created surface object.
Example 1: 2-argument function
f = @(x,y) sqrt (abs (x .* y)) ./ (1 + x.^2 + y.^2); ezsurf (f, [-3, 3]); |
Example 2: parametrically defined function
fx = @(s,t) cos (s) .* cos (t); fy = @(s,t) sin (s) .* cos (t); fz = @(s,t) sin (t); ezsurf (fx, fy, fz, [-pi, pi, -pi/2, pi/2], 20); |
Plot the surface and contour lines defined by a function.
f is a string, inline function, or function handle with two arguments
defining the function. By default the plot is over the meshed domain
-2*pi <= x | y <= 2*pi with 60 points in each dimension.
If three functions are passed, then plot the parametrically defined
function [fx (s, t), fy (s, t),
fz (s, t)].
If dom is a two element vector, it represents the minimum and maximum
values of both x and y. If dom is a four element vector,
then the minimum and maximum values are [xmin xmax ymin ymax].
n is a scalar defining the number of points to use in each dimension.
If the argument "circ" is given, then the function is plotted over
a disk centered on the middle of the domain dom.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a 2-element vector with a graphics handle for the created surface plot and a second handle for the created contour plot.
Example:
f = @(x,y) sqrt (abs (x .* y)) ./ (1 + x.^2 + y.^2); ezsurfc (f, [-3, 3]); |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Plot a 3-D unit cylinder.
The optional input r is a vector specifying the radius along the
unit z-axis. The default is [1 1] indicating radius 1 at Z == 0
and at Z == 1.
The optional input n determines the number of faces around the the circumference of the cylinder. The default value is 20.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
If outputs are requested cylinder returns three matrices in
meshgrid format, such that surf (x, y, z)
generates a unit cylinder.
Example:
[x, y, z] = cylinder (10:-1:0, 50);
surf (x, y, z);
title ("a cone");
|
Plot a 3-D unit sphere.
The optional input n determines the number of faces around the the circumference of the sphere. The default value is 20.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
If outputs are requested sphere returns three matrices in
meshgrid format such that surf (x, y, z)
generates a unit sphere.
Example:
[x, y, z] = sphere (40);
surf (3*x, 3*y, 3*z);
axis equal;
title ("sphere of radius 3");
|
Plot a 3-D ellipsoid.
The inputs xc, yc, zc specify the center of the ellipsoid. The inputs xr, yr, zr specify the semi-major axis lengths.
The optional input n determines the number of faces around the the circumference of the cylinder. The default value is 20.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
If outputs are requested ellipsoid returns three matrices in
meshgrid format, such that surf (x, y, z)
generates the ellipsoid.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can add titles, axis labels, legends, and arbitrary text to an existing plot. For example:
x = -10:0.1:10;
plot (x, sin (x));
title ("sin(x) for x = -10:0.1:10");
xlabel ("x");
ylabel ("sin (x)");
text (pi, 0.7, "arbitrary text");
legend ("sin (x)");
|
The functions grid and box may also be used to add grid
and border lines to the plot. By default, the grid is off and the
border lines are on.
Specify the string used as a title for the current axis.
An optional list of property/value pairs can be used to change the appearance of the created title text object.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created text object.
Display a legend for the current axes using the specified strings as labels.
Legend entries may be specified as individual character string arguments, a character array, or a cell array of character strings.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca. If the handles,
hobjs, are not specified then the legend’s strings will be associated
with the axes’ descendants. legend works on line graphs,
bar graphs, etc. A plot must exist before legend is called.
The optional parameter pos specifies the location of the legend as follows:
| pos | location of the legend | |
|---|---|---|
| north | center top | |
| south | center bottom | |
| east | right center | |
| west | left center | |
| northeast | right top (default) | |
| northwest | left top | |
| southeast | right bottom | |
| southwest | left bottom | |
| outside | can be appended to any location string |
The optional parameter orient determines if the key elements
are placed vertically or horizontally. The allowed values are
"vertical" (default) or "horizontal".
The following customizations are available using option:
"show"Show legend on the plot
"hide"Hide legend on the plot
"toggle" Toggles between "hide" and "show"
"boxon"Show a box around legend (default)
"boxoff"Hide the box around legend
"right"Place label text to the right of the keys (default)
"left"Place label text to the left of the keys
"off"Delete the legend object
The optional output values are
The graphics handle of the legend object.
Graphics handles to the text and line objects which make up the legend.
Graphics handles to the plot objects which were used in making the legend.
A cell array of strings of the labels in the legend.
The legend label text is either provided in the call to legend or
is taken from the DisplayName property of graphics objects. If no
labels or DisplayNames are available, then the label text is simply
"data1", "data2", …, "dataN".
Implementation Note: A legend is implemented as an additional axes object
of the current figure with the "tag" set to "legend".
Properties of the legend object may be manipulated directly by using
set.
Create a text object with text string at position x, y, (z) on the current axes.
Multiple locations can be specified if x, y, (z) are vectors. Multiple strings can be specified with a character matrix or a cell array of strings.
Optional property/value pairs may be used to control the appearance of the text.
The optional return value h is a vector of graphics handles to the created text objects.
See Text Properties for the properties that you can set.
Specify the string used to label the x-axis of the current axis.
An optional list of property/value pairs can be used to change the properties of the created text label.
If the first argument hax is an axes handle, then operate on
this axis rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created text object.
Add labels to the contours of a contour plot.
The contour levels are specified by the contour matrix c which is
returned by contour, contourc, contourf, and
contour3. Contour labels are rotated to match the local line
orientation and centered on the line. The position of labels along the
contour line is chosen randomly.
If the argument h is a handle to a contour group object, then label
this plot rather than the one in the current axes returned by gca.
By default, all contours are labeled. However, the contours to label can be
specified by the vector v. If the "manual" argument is
given then the contours to label can be selected with the mouse.
Additional property/value pairs that are valid properties of text objects
can be given and are passed to the underlying text objects. Moreover,
the contour group property "LabelSpacing" is available which
determines the spacing between labels on a contour to be specified. The
default is 144 points, or 2 inches.
The optional return value h is a vector of graphics handles to
the text objects representing each label.
The "userdata" property of the text objects contains the numerical
value of the contour label.
An example of the use of clabel is
[c, h] = contour (peaks (), -4 : 6); clabel (c, h, -4:2:6, "fontsize", 12); |
Control display of the axis border.
The argument may be either "on" or "off". If it is
omitted, the current box state is toggled.
If the first argument hax is an axes handle, then operate on
this axis rather than the current axes returned by gca.
Control the display of plot grid lines.
The function state input may be either "on" or "off".
If it is omitted, the current grid state is toggled.
When the first argument is "minor" all subsequent commands
modify the minor grid rather than the major grid.
If the first argument hax is an axes handle, then operate on
this axis rather than the current axes returned by gca.
To control the grid lines for an individual axis use the set
function. For example:
set (gca, "ygrid", "on"); |
Add a colorbar to the current axes.
A colorbar displays the current colormap along with numerical rulings so that the color scale can be interpreted.
The optional input loc determines the location of the colorbar. Valid values for loc are
"EastOutside"Place the colorbar outside the plot to the right. This is the default.
"East"Place the colorbar inside the plot to the right.
"WestOutside"Place the colorbar outside the plot to the left.
"West"Place the colorbar inside the plot to the left.
"NorthOutside"Place the colorbar above the plot.
"North"Place the colorbar at the top of the plot.
"SouthOutside"Place the colorbar under the plot.
"South"Place the colorbar at the bottom of the plot.
To remove a colorbar from a plot use any one of the following keywords for
the delete_option: "delete", "hide", "off".
If the argument "peer" is given, then the following argument is
treated as the axes handle in which to add the colorbar. Alternatively,
If the first argument hax is an axes handle, then the colorbar is
added to this axis, rather than the current axes returned by gca.
If the first argument hcb is a handle to a colorbar object, then operate on this colorbar directly.
Additional property/value pairs are passed directly to the underlying axes object.
The optional return value h is a graphics handle to the created colorbar object.
Implementation Note: A colorbar is created as an additional axes to the
current figure with the "tag" property set to "colorbar".
The created axes object has the extra property "location" which
controls the positioning of the colorbar.
See also: colormap.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave can display more than one plot in a single figure. The simplest
way to do this is to use the subplot function to divide the plot
area into a series of subplot windows that are indexed by an integer.
For example,
subplot (2, 1, 1) fplot (@sin, [-10, 10]); subplot (2, 1, 2) fplot (@cos, [-10, 10]); |
creates a figure with two separate axes, one displaying a sine wave and
the other a cosine wave. The first call to subplot divides the figure
into two plotting areas (two rows and one column) and makes the first plot
area active. The grid of plot areas created by subplot is
numbered in column-major order (top to bottom, left to right).
Set up a plot grid with rows by cols subwindows and set the
current axes for plotting (gca) to the location given by index.
If only one numeric argument is supplied, then it must be a three digit value specifying the number of rows in digit 1, the number of columns in digit 2, and the plot index in digit 3.
The plot index runs row-wise; First, all columns in a row are numbered and then the next row is filled.
For example, a plot with 2x3 grid will have plot indices running as follows:
+-----+-----+-----+ | 1 | 2 | 3 | +-----+-----+-----+ | 4 | 5 | 6 | +-----+-----+-----+ |
index may also be a vector. In this case, the new axis will enclose the grid locations specified. The first demo illustrates this:
demo ("subplot", 1)
|
The index of the subplot to make active may also be specified by its axes
handle, hax, returned from a previous subplot command.
If the option "align" is given then the plot boxes of the subwindows
will align, but this may leave no room for axis tick marks or labels.
If the option "replace" is given then the subplot axis will be
reset, rather than just switching the current axis for plotting to the
requested subplot.
The "position" property can be used to exactly position the subplot
axes within the current figure. The option pos is a 4-element vector
[x, y, width, height] that determines the location and size of the axes.
The values in pos are normalized in the range [0,1].
Any property/value pairs are passed directly to the underlying axes object.
If the output hax is requested, subplot returns the axis handle for
the subplot. This is useful for modifying the properties of a subplot
using set.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can open multiple plot windows using the figure function.
For example,
figure (1); fplot (@sin, [-10, 10]); figure (2); fplot (@cos, [-10, 10]); |
creates two figures, with the first displaying a sine wave and the second a cosine wave. Figure numbers must be positive integers.
Create a new figure window for plotting.
If no arguments are specified, a new figure with the next available number is created.
If called with an integer n, and no such numbered figure exists, then a new figure with the specified number is created. If the figure already exists then it is made visible and becomes the current figure for plotting.
Multiple property-value pairs may be specified for the figure object, but they must appear in pairs.
The optional return value h is a graphics handle to the created figure object.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
By default, Octave refreshes the plot window when a prompt is printed,
or when waiting for input. The
drawnow function is used to cause a plot window to be updated.
Update figure windows and their children. The event queue is flushed and
any callbacks generated are executed. With the optional argument
"expose", only graphic objects are updated and no other events or
callbacks are processed.
The third calling form of drawnow is for debugging and is
undocumented.
Only figures that are modified will be updated. The refresh
function can also be used to force an update of the current figure, even if
it is not modified.
Refresh a figure, forcing it to be redrawn.
When called without an argument the current figure is redrawn. Otherwise, the figure with graphic handle h is redrawn.
See also: drawnow.
Normally, high-level plot functions like plot or mesh call
newplot to initialize the state of the current axes so that the
next plot is drawn in a blank window with default property settings. To
have two plots superimposed over one another, use the hold
function. For example,
hold on; x = -10:0.1:10; plot (x, sin (x)); plot (x, cos (x)); hold off; |
displays sine and cosine waves on the same axes. If the hold state is off, consecutive plotting commands like this will only display the last plot.
Prepare graphics engine to produce a new plot.
This function is called at the beginning of all high-level plotting
functions. It is not normally required in user programs. newplot
queries the "NextPlot" field of the current figure and axis to
determine what to do.
| Figure NextPlot | Action |
|---|---|
"new" | Create a new figure and make it the current figure. |
"add" (default) | Add new graphic objects to the current figure. |
"replacechildren" | Delete child objects whose HandleVisibility is
set to "on". Set NextPlot property to "add". This
typically clears a figure, but leaves in place hidden objects such as
menubars. This is equivalent to clf. |
"replace" | Delete all child objects of the figure and
reset all figure properties to their defaults. However, the following
four properties are not reset: Position, Units, PaperPosition, PaperUnits.
This is equivalent to clf reset. |
| Axis NextPlot | Action |
|---|---|
"add" | Add new graphic objects to the current axes. This is
equivalent to hold on. |
"replacechildren" | Delete child objects whose HandleVisibility is
set to "on", but leave axis properties unmodified. This typically
clears a plot, but preserves special settings such as log scaling for
axes. This is equivalent to cla. |
"replace" (default) | Delete all child objects of the
axis and reset all axis properties to their defaults. However, the
following properties are not reset: Position, Units. This is equivalent
to cla reset. |
If the optional input hfig or hax is given then prepare the specified figure or axes rather than the current figure and axes.
The optional return value hax is a graphics handle to the created axes object (not figure).
Caution: Calling newplot may change the current figure and
current axis.
Toggle or set the "hold" state of the plotting engine which
determines whether new graphic objects are added to the plot or replace
the existing objects.
hold onRetain plot data and settings so that subsequent plot commands are displayed on a single graph.
hold allRetain plot line color, line style, data, and settings so that subsequent plot commands are displayed on a single graph with the next line color and style.
hold offRestore default graphics settings which clear the graph and reset axis properties before each new plot command. (default).
holdToggle the current hold state.
When given the additional argument hax, the hold state is modified
for this axis rather than the current axes returned by gca.
To query the current hold state use the ishold function.
Return true if the next plot will be added to the current plot, or false if the plot device will be cleared before drawing the next plot.
If the first argument is an axes handle hax or figure handle hfig then operate on this plot rather than the current one.
To clear the current figure, call the clf function. To clear the
current axis, call the cla function. To bring the current figure
to the top of the window stack, call the shg function. To delete
a graphics object, call delete on its index. To close the
figure window, call the close function.
Clear the current figure window.
clf operates by deleting child graphics objects with visible
handles (HandleVisibility = "on").
If the optional argument "reset" is specified, delete all child
objects including those with hidden handles and reset all figure
properties to their defaults. However, the following properties are not
reset: Position, Units, PaperPosition, PaperUnits.
If the first argument hfig is a figure handle, then operate on
this figure rather than the current figure returned by gcf.
The optional return value h is the graphics handle of the figure window that was cleared.
Clear the current axes.
cla operates by deleting child graphic objects with visible
handles (HandleVisibility = "on").
If the optional argument "reset" is specified, delete all child
objects including those with hidden handles and reset all axis properties
to their defaults. However, the following properties are not reset:
Position, Units.
If the first argument hax is an axes handle, then operate on
this axis rather than the current axes returned by gca.
Show the graph window.
Currently, this is the same as executing drawnow.
Delete the named file or graphics handle.
Deleting graphics objects is the proper way to remove features from a plot without clearing the entire figure.
Close figure window(s).
When called with no arguments, close the current figure. This is equivalent
to close (gcf). If the input h is a graphic handle, or vector
of graphics handles, then close each figure in h.
If the argument "all" is given then all figures with visible handles
(HandleVisibility = "on") are closed.
If the argument "all hidden" is given then all figures, including
hidden ones, are closed.
Implementation Note: close operates by calling the function specified
by the "closerequestfcn" property for each figure. By default, the
function closereq is used. It is possible that the function invoked
will delay or abort removing the figure. To remove a figure without
executing any callback functions use delete. When writing a callback
function to close a window do not use close to avoid recursion.
Close the current figure and delete all graphics objects associated with it.
By default, the "closerequestfcn" property of a new plot figure
points to this function.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
interpreter PropertyAll text objects—such as titles, labels, legends, and text—include
the property "interpreter", this property determines the manner in
which special control sequences in the text are rendered. If the interpreter
is set to "none", then no rendering occurs. Currently the
"latex" interpreter is not implemented and is equivalent to
"none".
The "tex" option implements a subset of TeX functionality when
rendering text. This allows the insertion of special glyphs such as Greek
characters or mathematical symbols. The special characters are inserted with
a code following a backslash (\) character, as in the table
tab:extended.
In addition, the formatting of the text can be changed within the string by using the codes
| \bf | Bold font | ||
| \it | Italic font | ||
| \sl | Oblique Font | ||
| \rm | Normal font |
These may be used in conjunction with the { and } characters to limit the change in the font to part of the string. For example,
xlabel ('{\bf H} = a {\bf V}')
|
where the character 'a' will not appear in a bold font. Note that to
avoid having Octave interpret the backslash characters in the strings,
the strings should be in single quotes.
It is also possible to change the fontname and size within the text
| \fontname{fontname} | Specify the font to use | ||
| \fontsize{size} | Specify the size of the font to use |
Finally, superscripting and subscripting can be controlled with the '^'
and '_' characters. If the '^' or '_' is followed by a
{ character, then all of the block surrounded by the { } pair is super- or
sub-scripted. Without the { } pair, only the character immediately following
the '^' or '_' is super- or sub-scripted.
| Greek Lowercase Letters | |||
| \alpha | \beta | \gamma | |
| \delta | \epsilon | \zeta | |
| \eta | \theta | \vartheta | |
| \iota | \kappa | \lambda | |
| \mu | \nu | \xi | |
| \o | \pi | \varpi | |
| \rho | \sigma | \varsigma | |
| \tau | \upsilon | \phi | |
| \chi | \psi | \omega | |
| Greek Uppercase Letters | |||
| \Gamma | \Delta | \Theta | |
| \Lambda | \Xi | \Pi | |
| \Sigma | \Upsilon | \Phi | |
| \Psi | \Omega | ||
| Misc Symbols Type Ord | |||
| \aleph | \wp | \Re | |
| \Im | \partial | \infty | |
| \prime | \nabla | \surd | |
| \angle | \forall | \exists | |
| \neg | \clubsuit | \diamondsuit | |
| \heartsuit | \spadesuit | ||
| “Large” Operators | |||
| \int | |||
| Binary Operators | |||
| \pm | \cdot | \times | |
| \ast | \circ | \bullet | |
| \div | \cap | \cup | |
| \vee | \wedge | \oplus | |
| \otimes | \oslash | ||
| Relations | |||
| \leq | \subset | \subseteq | |
| \in | \geq | \supset | |
| \supseteq | \ni | \mid | |
| \equiv | \sim | \approx | |
| \cong | \propto | \perp | |
| Arrows | |||
| \leftarrow | \Leftarrow | \rightarrow | |
| \Rightarrow | \leftrightarrow | \uparrow | |
| \downarrow | |||
| Openings and Closings | |||
| \lfloor | \langle | \lceil | |
| \rfloor | \rangle | \rceil | |
| Alternate Names | |||
| \neq | |||
| Other | |||
| \ldots | \0 | \copyright | |
| \deg |
Table 15.1: Available special characters in TeX mode
A complete example showing the capabilities of the extended text is
x = 0:0.01:3;
plot (x, erf (x));
hold on;
plot (x,x,"r");
axis ([0, 3, 0, 1]);
text (0.65, 0.6175, strcat ('\leftarrow x = {2/\surd\pi',
' {\fontsize{16}\int_{\fontsize{8}0}^{\fontsize{8}x}}',
' e^{-t^2} dt} = 0.6175'))
|
The result of which can be seen in fig:extendedtext
Figure 15.7: Example of inclusion of text with the TeX interpreter
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The print command allows you to send plots to you printer and
to save plots in a variety of formats. For example,
print -dpsc |
prints the current figure to a color PostScript printer. And,
print -deps foo.eps |
saves the current figure to an encapsulated PostScript file called ‘foo.eps’.
Print a plot, or save it to a file.
Both output formatted for printing (PDF and PostScript), and many bitmapped and vector image formats are supported.
filename defines the name of the output file. If the file name has no suffix, one is inferred from the specified device and appended to the file name. If no filename is specified, the output is sent to the printer.
h specifies the handle of the figure to print. If no handle is specified the current figure is used.
For output to a printer, PostScript file, or PDF file,
the paper size is specified by the figure’s papersize
property. The location and size of the image on the page are
specified by the figure’s paperposition property. The
orientation of the page is specified by the figure’s
paperorientation property.
The width and height of images are specified by the figure’s
paperpositon(3:4) property values.
The print command supports many options:
-fhSpecify the handle, h, of the figure to be printed. The default is the current figure.
-PprinterSet the printer name to which the plot is sent if no filename is specified.
-Gghostscript_command Specify the command for calling Ghostscript. For Unix and Windows
the defaults are "gs" and "gswin32c", respectively.
-color-monoColor or monochrome output.
-solid-dashedForce all lines to be solid or dashed, respectively.
-portrait-landscape Specify the orientation of the plot for printed output. For
non-printed output the aspect ratio of the output corresponds to
the plot area defined by the "paperposition" property in the
orientation specified. This option is equivalent to changing
the figure’s "paperorientation" property.
-TextAlphaBits=n-GraphicsAlphaBits=nOctave is able to produce output for various printers, bitmaps, and vector formats by using Ghostscript. For bitmap and printer output anti-aliasing is applied using Ghostscript’s TextAlphaBits and GraphicsAlphaBits options. The default number of bits for each is 4. Allowed values for N are 1, 2, or 4.
-ddeviceThe available output format is specified by the option device, and is one of:
psps2pscpsc2PostScript (level 1 and 2, mono and color). The FLTK graphics toolkit generates PostScript level 3.0.
epseps2epscepsc2Encapsulated PostScript (level 1 and 2, mono and color). The FLTK graphic toolkit generates PostScript level 3.0.
texepslatexepslatexstandalonepstexpslatexpdflatex Generate a LaTeX (or TeX) file for labels and eps/ps/pdf
for graphics. The file produced by epslatexstandalone can be
processed directly by LaTeX. The other formats are intended to
be included in a LaTeX (or TeX) document. The tex device
is the same as the epslatex device. The pdflatex device
is only available for the FLTK graphics toolkit.
tikzGenerate a LaTeX file using PGF/TikZ. For the FLTK toolkit the result is PGF.
illaifmAdobe Illustrator (Obsolete for Gnuplot versions > 4.2)
cdrcorelCorelDraw
dxfAutoCAD
emfmetaMicrosoft Enhanced Metafile
figXFig. For the Gnuplot graphics toolkit, the additional options ‘-textspecial’ or ‘-textnormal’ can be used to control whether the special flag should be set for the text in the figure. (default is ‘-textnormal’)
hpglHP plotter language
mfMetafont
pngPortable network graphics
jpgjpegJPEG image
gifGIF image (only available for the Gnuplot graphics toolkit)
pbmPBMplus
svgScalable vector graphics
pdfPortable document format
If the device is omitted, it is inferred from the file extension, or if there is no filename it is sent to the printer as PostScript.
-dghostscript_deviceAdditional devices are supported by Ghostscript. Some examples are;
ljet2pHP LaserJet IIP
ljet3HP LaserJet III
deskjetHP DeskJet and DeskJet Plus
cdj550HP DeskJet 550C
paintjetHP PointJet
pcx24b24-bit color PCX file format
ppmPortable Pixel Map file format
pdfwriteProduces pdf output from eps
For a complete list, type system ("gs -h") to see what formats
and devices are available.
When Ghostscript output is sent to a printer the size is determined
by the figure’s "papersize" property. When the output
is sent to a file the size is determined by the plot box defined by
the figure’s "paperposition" property.
-appendAppend PostScript or PDF output to a pre-existing file of the same type.
-rNUM Resolution of bitmaps in pixels per inch. For both metafiles and
SVG the default is the screen resolution; for other formats it is 150 dpi.
To specify screen resolution, use "-r0".
-loose-tightForce a tight or loose bounding box for eps files. The default is loose.
-previewAdd a preview to eps files. Supported formats are:
-interchangeProvide an interchange preview.
-metalfileProvide a metafile preview.
-pictProvide pict preview.
-tiffProvide a tiff preview.
-Sxsize,ysize Plot size in pixels for EMF, GIF, JPEG, PBM, PNG, and SVG. For
PS, EPS, PDF, and other vector formats the plot size is in points.
This option is equivalent to changing the size of the plot box
associated with the "paperposition" property. When using the
command form of the print function you must quote the
xsize,ysize option. For example, by writing "-S640,480".
-Ffontname-Ffontname:size-F:sizeUse fontname and/or fontsize for all text. fontname is ignored for some devices: dxf, fig, hpgl, etc.
The filename and options can be given in any order.
Example: Print to a file using the svg device.
figure (1); clf (); surf (peaks); print -dsvg figure1.svg |
Example: Print to an HP DeskJet 550C.
clf (); surf (peaks); print -dcdj550 |
Save graphic object h to the file filename in graphic format fmt.
fmt should be one of the following formats:
psPostScript
epsEncapsulated PostScript
jpgJPEG Image
pngPNG Image
emfEnhanced Meta File
pdfPortable Document Format
All device formats specified in print may also be used. If
fmt is omitted it is extracted from the extension of filename.
The default format is "pdf".
clf (); surf (peaks); saveas (1, "figure1.png"); |
Query or set the print orientation for figure hfig.
Valid values for orientation are "portrait",
"landscape", and "tall".
The "landscape" option changes the orientation so the plot width
is larger than the plot height. The "paperposition" is also
modified so that the plot fills the page, while leaving a 0.25 inch border.
The "tall" option sets the orientation to "portrait" and
fills the page with the plot, while leaving a 0.25 inch border.
The "portrait" option (default) changes the orientation so the plot
height is larger than the plot width. It also restores the default
"paperposition" property.
When called with no arguments, return the current print orientation.
If the argument hfig is omitted, then operate on the current figure
returned by gcf.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The user can select points on a plot with the ginput function or
selection the position at which to place text on the plot with the
gtext function using the mouse. Menus may also be created
and populated with specific user commands via the uimenu function.
Return the position and type of mouse button clicks and/or key strokes in the current figure window.
If n is defined, then capture n events before returning.
When n is not defined ginput will loop until the return key
<RET> is pressed.
The return values x, y are the coordinates where the mouse was clicked in the units of the current axes. The return value button is 1, 2, or 3 for the left, middle, or right button. If a key is pressed the ASCII value is returned in button.
See also: gtext, waitforbuttonpress.
Wait for mouse click or key press over the current figure window.
The return value of b is 0 if a mouse button was pressed or 1 if a key was pressed.
Place text on the current figure using the mouse.
The text is defined by the string s. If s is a cell string organized as a row vector then each string of the cell array is written to a separate line. If s is organized as a column vector then one string element of the cell array is placed for every mouse click.
Optional property/value pairs are passed directly to the underlying text objects.
The optional return value h is a graphics handle to the created text object(s).
Create a uimenu object and return a handle to it. If h is omitted then a top-level menu for the current figure is created. If h is given then a submenu relative to h is created.
uimenu objects have the following specific properties:
"accelerator"A string containing the key combination together with CTRL to execute this
menu entry (e.g., "x" for CTRL+x).
"callback"Is the function called when this menu entry is executed. It can be either a
function string (e.g., "myfun"), a function handle (e.g., @myfun)
or a cell array containing the function handle and arguments for the
callback function (e.g., {@myfun, arg1, arg2}).
"checked"Can be set "on" or "off". Sets a mark at this menu entry.
"enable"Can be set "on" or "off". If disabled the menu entry
cannot be selected and it is grayed out.
"foregroundcolor"A color value setting the text color for this menu entry.
"label"A string containing the label for this menu entry. A "&"-symbol
can be used to mark the "accelerator" character (e.g.,
"E&xit")
"position"An scalar value containing the relative menu position. The entry with the lowest value is at the first position starting from left or top.
"separator"Can be set "on" or "off". If enabled it draws a separator
line above the current position. It is ignored for top level entries.
Examples:
f = uimenu ("label", "&File", "accelerator", "f");
e = uimenu ("label", "&Edit", "accelerator", "e");
uimenu (f, "label", "Close", "accelerator", "q", ...
"callback", "close (gcf)");
uimenu (e, "label", "Toggle &Grid", "accelerator", "g", ...
"callback", "grid (gca)");
|
See also: figure.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The functions sombrero and peaks provide a way to check
that plotting is working. Typing either sombrero or peaks
at the Octave prompt should display a three-dimensional plot.
Plot the familiar 3-D sombrero function.
The function plotted is
z = sin (sqrt (x^2 + y^2)) / (sqrt (x^2 + y^2)) |
Called without a return argument, sombrero plots the surface of the
above function over the meshgrid [-8,8] using surf.
If n is a scalar the plot is made with n grid lines. The default value for n is 41.
When called with output arguments, return the data for the function
evaluated over the meshgrid. This can subsequently be plotted with
surf (x, y, z).
Plot a function with lots of local maxima and minima.
The function has the form
f(x,y) = 3*(1-x)^2*exp(-x^2 - (y+1)^2) ...
- 10*(x/5 - x^3 - y^5)*exp(-x^2-y^2) ...
- 1/3*exp(-(x+1)^2 - y^2)
Called without a return argument, peaks plots the surface of the
above function using surf.
If n is a scalar, peaks plots the value of the above
function on an n-by-n mesh over the range [-3,3]. The
default value for n is 49.
If n is a vector, then it represents the grid values over which to calculate the function. If x and y are specified then the function value is calculated over the specified grid of vertices.
When called with output arguments, return the data for the function
evaluated over the meshgrid. This can subsequently be plotted with
surf (x, y, z).
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 15.3.1 Introduction to Graphics Structures | ||
| 15.3.2 Graphics Objects | ||
| 15.3.3 Graphics Object Properties | ||
| 15.3.4 Searching Properties | ||
| 15.3.5 Managing Default Properties |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The graphics functions use pointers, which are of class graphics_handle, in
order to address the data structures which control graphical displays. A
graphics handle may point any one of a number of different object types. The
objects are the graphics data structures. The types of objects are:
figure, axes, line, text, patch,
surface, text and image.
Each of these objects has a function by the same name. and, each of these
functions returns a graphics handle pointing to an object of corresponding
type. In addition there are several functions which operate on properties of
the graphics objects and which return handles: the functions plot and
plot3 return a handle pointing to an object of type line, the function
subplot returns a handle pointing to an object of type axes, the
function fill returns a handle pointing to an object of type patch, the
functions area, bar, barh, contour,
contourf, contour3, surf, mesh, surfc,
meshc, errorbar, quiver, quiver3, scatter,
scatter3, stair, stem, stem3 each return a handle
as documented in Data Sources.
The graphics objects are arranged in a hierarchy:
1. The root is at 0. i.e., get (0) returns the properties of the root
object.
2. Below the root are figure objects.
3. Below the figure objects are axes.
4. Below the axes objects are
line, text, patch,
surface, and image objects.
Graphics handles may be distinguished from function handles
(see section Function Handles) by means of the function ishandle.
ishandle returns true if its argument is a handle of a graphics object.
In addition, the figure object may be tested using isfigure.
isfigure returns true only if its argument is a handle of a figure. The
whos function can be used to show the object type of each currently
defined graphics handle. (Note: this is not true today, but it is, I hope,
considered an error in whos. It may be better to have whos just show
graphics_handle as the class, and provide a new function which, given a
graphics handle, returns its object type. This could generalize the ishandle()
functions and, in fact, replace them.)
The get and set commands are used to obtain and set the values of
properties of graphics objects. In addition, the get command may be
used to obtain property names.
For example, the property "type" of the graphics object pointed to by
the graphics handle h may be displayed by:
get (h, "type") |
The properties and their current values are returned by get (h)
where h is a handle of a graphics object. If only the names of the
allowed properties are wanted they may be displayed by:
get (h, "").
Thus, for example:
h = figure (); get (h, "type") ans = figure get (h, ""); error: get: ambiguous figure property name ; possible matches: __enhanced__ hittest resize __graphics_toolkit__ integerhandle resizefcn __guidata__ interruptible selected __modified__ inverthardcopy selectionhighlight __myhandle__ keypressfcn selectiontype __plot_stream__ keyreleasefcn tag alphamap menubar toolbar beingdeleted mincolormap type busyaction name uicontextmenu buttondownfcn nextplot units children numbertitle userdata clipping outerposition visible closerequestfcn paperorientation windowbuttondownfcn color paperposition windowbuttonmotionfcn colormap paperpositionmode windowbuttonupfcn createfcn papersize windowkeypressfcn currentaxes papertype windowkeyreleasefcn currentcharacter paperunits windowscrollwheelfcn currentobject parent windowstyle currentpoint pointer wvisual deletefcn pointershapecdata wvisualmode dockcontrols pointershapehotspot xdisplay doublebuffer position xvisual filename renderer xvisualmode handlevisibility renderermode |
The root figure has index 0. Its properties may be displayed by:
get (0, "").
The uses of get and set are further explained in
get, set.
Return true if prop is a property of the object with handle h.
h may also be an array of handles in which case res will be a logical array indicating whether each handle has the property prop.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The hierarchy of graphics objects was explained above. See section Introduction to Graphics Structures. Here the specific objects are described, and the properties contained in these objects are discussed. Keep in mind that graphics objects are always referenced by handle.
the top level of the hierarchy and the parent of all figure objects. The handle index of the root figure is 0.
A figure window.
A set of axes. This object is a child of a figure object and may be a parent of line, text, image, patch, or surface objects.
A line in two or three dimensions.
Text annotations.
A bitmap image.
A filled polygon, currently limited to two dimensions.
A three-dimensional surface.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can create axes, line, patch, and surface objects directly using the
axes, line, patch, fill, and surface
functions. These objects become children of the current axes object.
Create an axes object and return a handle to it, or set the current axes to hax.
Called without any arguments, or with property/value pairs, construct a new axes. For accepted properties and corresponding values, see set.
Called with a single axes handle argument hax, the function makes hax the current axis. It also restacks the axes in the corresponding figure so that hax is the first entry in the list of children. This causes hax to be displayed on top of any other axes objects (Z-order stacking).
See also: gca, set, get.
Create line object from x and y (and possibly z) and insert in the current axes.
Multiple property-value pairs may be specified for the line object, but they must appear in pairs.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle (or vector of handles) to the line objects created.
Create patch object in the current axes with vertices at locations (x, y) and of color c.
If the vertices are matrices of size MxN then each polygon patch has M vertices and a total of N polygons will be created. If some polygons do not have M vertices use NaN to represent "no vertex". If the z input is present then 3-D patches will be created.
The color argument c can take many forms. To create polygons
which all share a single color use a string value (e.g., "r" for
red), a scalar value which is scaled by caxis and indexed into the
current colormap, or a 3-element RGB vector with the precise TrueColor.
If c is a vector of length N then the ith polygon will have a color
determined by scaling entry c(i) according to caxis and then
indexing into the current colormap. More complicated coloring situations
require directly manipulating patch property/value pairs.
Instead of specifying polygons by matrices x and y, it is
possible to present a unique list of vertices and then a list of polygon
faces created from those vertices. In this case the
"Vertices" matrix will be an Nx2 (2-D patch) or
Nx3 (3-D path). The MxN "Faces" matrix
describes M polygons having N vertices—each row describes a
single polygon and each column entry is an index into the
"Vertices" matrix to identify a vertex. The patch object
can be created by directly passing the property/value pairs
"Vertices"/verts, "Faces"/faces as
inputs.
A third input form is to create a structure fv with the fields
"vertices", "faces", and optionally
"facevertexcdata".
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created patch object.
Implementation Note: Patches are highly configurable objects. To truly
customize them requires setting patch properties directly. Useful patch
properties are: "cdata", "edgecolor",
"facecolor", "faces", "facevertexcdata".
Create one or more filled 2-D polygons.
The inputs x and y are the coordinates of the polygon vertices.
If the inputs are matrices then the rows represent different vertices and
each column produces a different polygon. fill will close any open
polygons before plotting.
The input c determines the color of the polygon. The simplest form
is a single color specification such as a plot format or an
RGB-triple. In this case the polygon(s) will have one unique color. If
c is a vector or matrix then the color data is first scaled using
caxis and then indexed into the current colormap. A row vector will
color each polygon (a column from matrices x and y) with a
single computed color. A matrix c of the same size as x and
y will compute the color of each vertex and then interpolate the face
color between the vertices.
Multiple property/value pairs for the underlying patch object may be specified, but they must appear in pairs.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a vector of graphics handles to the created patch objects.
Example: red square
vertices = [0 0
1 0
1 1
0 1];
fill (vertices(:,1), vertices(:,2), "r");
axis ([-0.5 1.5, -0.5 1.5])
axis equal
|
Create a surface graphic object given matrices x and y from
meshgrid and a matrix of values z corresponding to the
x and y coordinates of the surface.
If x and y are vectors, then a typical vertex is
(x(j), y(i), z(i,j)). Thus, columns of z correspond
to different x values and rows of z correspond to different
y values. If only a single input z is given then x is
taken to be 1:rows (z) and y is
1:columns (z).
Any property/value input pairs are assigned to the surface object.
If the first argument hax is an axes handle, then plot into this axis,
rather than the current axes returned by gca.
The optional return value h is a graphics handle to the created surface object.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
To determine whether a variable is a graphics object index, or an index
to an axes or figure, use the functions ishandle, isaxes, and
isfigure.
Return true if h is a graphics handle and false otherwise.
h may also be a matrix of handles in which case a logical array is returned that is true where the elements of h are graphics handles and false where they are not.
Return true if h is a graphics handle and false otherwise.
This function is equivalent to ishandle and is provided for
compatibility with MATLAB.
See also: ishandle.
Return true if h is an axes graphics handle and false otherwise.
If h is a matrix then return a logical array which is true where the elements of h are axes graphics handles and false where they are not.
Return true if h is a figure graphics handle and false otherwise.
If h is a matrix then return a logical array which is true where the elements of h are figure graphics handles and false where they are not.
The function gcf returns an index to the current figure object,
or creates one if none exists. Similarly, gca returns the
current axes object, or creates one (and its parent figure object) if
none exists.
Return a handle to the current figure.
The current figure is the default target for graphics output. If multiple
figures exist, gcf returns the last created figure or the last figure
that was clicked on with the mouse.
If a current figure does not exist, create one and return its handle. The handle may then be used to examine or set properties of the figure. For example,
fplot (@sin, [-10, 10]); fig = gcf (); set (fig, "numbertitle", "off", "name", "sin plot") |
plots a sine wave, finds the handle of the current figure, and then renames the figure window to describe the contents.
Note: To find the current figure without creating a new one if it does not
exist, query the "CurrentFigure" property of the root graphics
object.
get (0, "currentfigure"); |
Return a handle to the current axis object.
The current axis is the default target for graphics output. In the case
of a figure with multiple axes, gca returns the last created axes
or the last axes that was clicked on with the mouse.
If no current axes object exists, create one and return its handle. The handle may then be used to examine or set properties of the axes. For example,
ax = gca (); set (ax, "position", [0.5, 0.5, 0.5, 0.5]); |
creates an empty axes object and then changes its location and size in the figure window.
Note: To find the current axis without creating a new axes object if it
does not exist, query the "CurrentAxes" property of a figure.
get (gcf, "currentaxes"); |
Return a handle to the current object of the current figure, or a handle to the current object of the figure with handle fig.
The current object of a figure is the object that was last clicked on. It
is stored in the "CurrentObject" property of the target figure.
If the last mouse click did not occur on any child object of the figure, then the current object is the figure itself.
If no mouse click occurred in the target figure, this function returns an empty matrix.
Programming Note: The value returned by this function is not necessarily the
same as the one returned by gcbo during callback execution. An
executing callback can be interrupted by another callback and the current
object may be changed.
The get and set functions may be used to examine and set
properties for graphics objects. For example,
get (0)
⇒ ans =
{
type = root
currentfigure = [](0x0)
children = [](0x0)
visible = on
…
}
|
returns a structure containing all the properties of the root figure.
As with all functions in Octave, the structure is returned by value, so
modifying it will not modify the internal root figure plot object. To
do that, you must use the set function. Also, note that in this
case, the currentfigure property is empty, which indicates that
there is no current figure window.
The get function may also be used to find the value of a single
property. For example,
get (gca (), "xlim")
⇒ [ 0 1 ]
|
returns the range of the x-axis for the current axes object in the current figure.
To set graphics object properties, use the set function. For example,
set (gca (), "xlim", [-10, 10]); |
sets the range of the x-axis for the current axes object in the current figure to ‘[-10, 10]’. Additionally, calling set with a graphics object index as the only argument returns a structure containing the default values for all the properties for the given object type. For example,
set (gca ()) |
returns a structure containing the default property values for axes objects.
Return the value of the named property p from the graphics handle h. If p is omitted, return the complete property list for h. If h is a vector, return a cell array including the property values or lists respectively.
See also: set.
Set named property values for the graphics handle (or vector of graphics handles) h. There are three ways how to give the property names and values:
Here, each property is a string containing the property name, each value is a value of the appropriate type for the property.
In this case, the number of columns of values must match the number of elements in properties. The first column of values contains values for the first entry in properties, etc. The number of rows of values must be 1 or match the number of elements of h. In the first case, each handle in h will be assigned the same values. In the latter case, the first handle in h will be assigned the values from the first row of values and so on.
Here, the field names of pv represent the property names, and the field values give the property values. In contrast to the previous case, all elements of pv will be set in all handles in h independent of the dimensions of pv.
See also: get.
Return the first ancestor of handle object h whose type matches type, where type is a character string. If type is a cell array of strings, return the first parent whose type matches any of the given type strings.
If the handle object h itself is of type type, return h.
If "toplevel" is given as a third argument, return the highest
parent in the object hierarchy that matches the condition, instead
of the first (nearest) one.
Find all children, including hidden children, of a graphics object.
This function is similar to get (h, "children"), but also returns
hidden objects (HandleVisibility = "off"). If handles is a
scalar, h will be a vector. Otherwise, h will be a cell
matrix of the same size as handles and each cell will contain a
vector of handles.
Find all visible figures that are currently off the screen and move them onto the screen.
Figures can be printed or saved in many graphics formats with print and
saveas. Occasionally, however, it may be useful to save the original
Octave handle graphic directly so that further modifications can be made such
as modifying a title or legend.
This can be accomplished with the following functions by
fig_struct = hdl2struct (gcf);
save myplot.fig -struct fig_struct;
…
fig_struct = load ("myplot.fig");
struct2hdl (fig_struct);
|
Return a structure, s, whose fields describe the properties of the object, and its children, associated with the handle, h.
The fields of the structure s are "type", "handle",
"properties", "children", and "special".
See also: struct2hdl, findobj.
Construct a graphics handle object h from the structure s.
The structure must contain the fields "handle", "type",
"children", "properties", and "special". If the
handle of an existing figure or axes is specified, p, the new object
will be created as a child of that object. If no parent handle is provided
then a new figure and the necessary children will be constructed using the
default values from the root figure.
A third boolean argument hilev can be passed to specify whether the function should preserve listeners/callbacks, e.g., for legends or hggroups. The default is false.
See also: hdl2struct, findobj.
Construct a copy of the graphic object associated with handle horig and return a handle hnew to the new object.
If a parent handle hparent (root, figure, axes, or hggroup) is specified, the copied object will be created as a child of hparent.
See also: struct2hdl, hdl2struct, findobj.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In this Section the object properties are discussed in detail, starting with the root figure properties and continuing through the graphics object hierarchy.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The root figure properties are:
__modified__— Values: "on", "off"
__myhandle__beingdeleted— Values: "on", "off"
busyactionbuttondownfcncallbackobjectchildrenclipping — Values: "on", "off"
createfcncurrentfiguredeletefcnhandlevisibility— Values: "on", "off"
hittest— Values: "on", "off"
interruptible— Values: "on", "off"
parentscreendepthscreenpixelsperinchscreensizeselectedselectionhighlightscreendepthscreenpixelsperinchshowhiddenhandles— Values: "on", "off"
tagtypeuicontextmenuunitsuserdatavisible| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The figure properties are:
__graphics_toolkit__— The graphics toolkit currently in use.
__enhanced____modified____myhandle____plot_stream__alphamapbeingdeleted— Values: "on", "off"
busyactionbuttondownfcnchildrenHandle to children.
clipping— Values: "on", "off"
closerequestfcn— Handle of function to call on close.
colorcolormapAn N-by-3 matrix containing the color map for the current axes.
paperorientationcreatefcncurrentaxesHandle to graphics object of current axes.
currentcharactercurrentobjectcurrentpointHolds the coordinates of the point over which the mouse pointer was when
the mouse button was pressed. If a mouse callback function is defined,
"currentpoint" holds the coordinates of the point over which the
mouse pointer is when the function gets called.
deletefcndockcontrols— Values: "on", "off"
doublebuffer— Values: "on", "off"
filenamehandlevisibility— Values: "on", "off"
hittestintegerhandleinterruptible— Values: "on", "off"
inverthardcopykeypressfcnsee "keypressfcn"
keyreleasefcnWith "keypressfcn", the keyboard callback functions. These
callback functions get called when a key is pressed/released
respectively. The functions are called with two input arguments. The
first argument holds the handle of the calling figure. The second
argument holds the event structure which has the following members:
CharacterThe ASCII value of the key
Keylowercase value of the key
ModifierA cell array containing strings representing the modifiers pressed with
the key. Possible values are "shift", "alt", and
"control".
menubarmincolormapnamenextplotMay be one of
"new""add""replace""replacechildren"numbertitlepaperorientationIndicates the orientation for printing. Either "landscape" or
"portrait".
paperpositionpaperpositionmodepapersizepapertypepaperunitspointerpointershapecdatapointershapehotspotpositionrendererrenderermoderesizeresizefcnselectedselectionhighlight— Values: "on", "off"
selectiontypetagtoolbartypeunitsuserdatavisibleEither "on" or "off" to toggle display of the figure.
windowbuttondownfcnSee "windowbuttonupfcn"
windowbuttonmotionfcnSee "windowbuttonupfcn"
windowbuttonupfcnWith "windowbuttondownfcn" and "windowbuttonmotionfcn",
the mouse callback functions. These callback functions get called when
the mouse button is pressed, dragged, and released respectively. When
these callback functions are called, the "currentpoint" property
holds the current coordinates of the cursor.
windowscrollwheelfcnwindowstylewvisualwvisualmodexdisplayxvisualxvisualmode| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The axes properties are:
__modified____myhandle__activepositionpropertyalimalimmodeambientlightcolorbeingdeletedboxBox surrounding axes.
— Values: "on", "off"
busyactionbuttondownfcncamerapositioncamerapositionmodecameratargetcameratargetmodecameraupvectorcameraupvectormodecameraviewanglecameraviewanglemodechildrenclimTwo-element vector defining the limits for the c axis of
an image. See pcolor property.
Setting this property also forces the corresponding mode
property to be set to "manual".
climmodeEither "manual" or "auto".
clippingcolorcolorordercreatefcncurrentpointHolds the coordinates of the point over which the mouse pointer was when
the mouse button was pressed. If a mouse callback function is defined,
"currentpoint" holds the coordinates of the point over which the
mouse pointer is when the function gets called.
dataaspectratioA two-element vector specifying the relative height and width of the
data displayed in the axes. Setting dataaspectratio to ‘1,
2]’ causes the length of one unit as displayed on the y-axis to be the
same as the length of 2 units on the x-axis. Setting
dataaspectratio also forces the dataaspectratiomode
property to be set to "manual".
dataaspectratiomodeEither "manual" or "auto".
deletefcndrawmodefontanglefontnamefontsizefontunitsfontweightgridlinestylehandlevisibilityhittestinterpreterinterruptiblelayerlinestyleorderlinewidthminorgridlinestylenextplotMay be one of
"add""replace""replacechildren"outerpositionA vector specifying the position of the plot, including titles, axes and
legend. The four elements of the vector are the coordinates of the
lower left corner and width and height of the plot, in units normalized
to the width and height of the plot window. For example, [0.2,
0.3, 0.4, 0.5] sets the lower left corner of the axes at (0.2,
0.3) and the width and height to be 0.4 and 0.5 respectively. See also
the position property.
parentplotboxaspectratioplotboxaspectratiomodepositionA vector specifying the position of the plot, excluding titles, axes and
legend. The four elements of the vector are the coordinates of the
lower left corner and width and height of the plot, in units normalized
to the width and height of the plot window. For example, [0.2,
0.3, 0.4, 0.5] sets the lower left corner of the axes at (0.2,
0.3) and the width and height to be 0.4 and 0.5 respectively. See also
the outerposition property.
projectionselectedselectionhighlighttagtickdirtickdirmodeticklengthtightinsettitleIndex of text object for the axes title.
typeuicontextmenuunitsuserdataviewA three element vector specifying the view point for three-dimensional plots.
visibleEither "on" or "off" to toggle display of the axes.
x_normrendertransformx_projectiontransformx_rendertransformx_viewporttransformx_viewtransformxaxislocationEither "top" or "bottom".
xcolorxdirEither "forward" or "reverse".
xgridEither "on" or "off" to toggle display of grid lines.
xlabelIndices to text objects for the axes labels.
xlimTwo-element vector defining the limits for the x-axis.
Setting this property also forces the corresponding mode
property to be set to "manual".
xlimmodeEither "manual" or "auto".
xminorgridEither "on" or "off" to toggle display of minor grid lines.
xminortickxscaleEither "linear" or "log".
xtickSet position of tick marks.
Setting this property also forces the corresponding mode
property to be set to "manual".
xticklabelSetting this property also forces the corresponding mode
property to be set to "manual".
xticklabelmodeEither "manual" or "auto".
xtickmodeEither "manual" or "auto".
yaxislocationEither "left" or "right"
ycolorydirEither "forward" or "reverse".
ygridEither "on" or "off" to toggle display of grid lines.
ylabelIndices to text objects for the axes labels.
ylimTwo-element vectors defining the limits for the x, y, and z axes and the
Setting one of these properties also forces the corresponding mode
property to be set to "manual".
ylimmodeEither "manual" or "auto".
yminorgridEither "on" or "off" to toggle display of minor grid lines.
yminortickyscaleEither "linear" or "log".
ytickSet position of tick marks.
Setting this property also forces the corresponding mode
property to be set to "manual".
yticklabelSetting this property also forces the corresponding mode
property to be set to "manual".
yticklabelmodeEither "manual" or "auto".
ytickmodeEither "manual" or "auto".
zcolorzdirEither "forward" or "reverse".
zgridEither "on" or "off" to toggle display of grid lines.
zlabelIndices to text objects for the axes labels.
zlimTwo-element vector defining the limits for z-axis.
Setting this property also forces the corresponding mode
property to be set to "manual".
zlimmodeEither "manual" or "auto".
zminorgridEither "on" or "off" to toggle display of minor grid lines.
zminortickzscaleEither "linear" or "log".
ztickSet position of tick marks.
Setting this property also forces the corresponding mode
property to be set to "manual".
zticklabelSetting this property also forces the corresponding mode
property to be set to "manual".
zticklabelmodeEither "manual" or "auto".
ztickmodeEither "manual" or "auto".
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The line properties are:
__modified____myhandle__beingdeletedbusyactionbuttondownfcnchildrenclippingcolorThe RGB color of the line, or a color name. See section Colors.
createfcndeletefcndisplaynameThe text of the legend entry corresponding to this line.
erasemodehandlevisibilityhittestinterpreterinterruptibleldataThe lower errorbar in the y direction to be plotted.
linestylelinewidthSee section Line Styles.
linewidthmarkermarkeredgecolormarkerfacecolormarkersizeSee section Marker Styles.
parentselectedselectionhighlighttagtypeudataThe upper errorbar in the y direction to be plotted.
uicontextmenuuserdatavisiblexdataThe data to be plotted.
xdatasourcexldataThe lower errorbar to be plotted.
xlimxlimincludexudataThe upper errorbar to be plotted.
ydataThe data to be plotted.
ydatasourceylimylimincludezdataThe data to be plotted.
zdatasourcezlimzliminclude| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The text properties are:
__modified____myhandle__backgroundcolorbeingdeletedbusyactionbuttondownfcnchildrenclippingcolorThe color of the text. See section Colors.
createfcndeletefcndisplaynameThe text of the legend entry corresponding to this line.
edgecoloreditingerasemodefontangleFlag whether the font is italic or normal. Valid values are "normal",
"italic", and "oblique".
fontnameThe font used for the text.
fontsizeThe size of the font, in points to use.
fontunitsfontweightFlag whether the font is bold, etc. Valid values are "normal",
"bold", "demi", or "light".
handlevisibilityhittesthorizontalalignmentMay be "left", "center", or "right".
interpreterDetermines how the text is rendered. Valid values are "none",
"tex", or "latex".
interruptiblelinestylelinewidthmarginparentpositionThe coordinates of the text object.
rotationThe angle of rotation for the displayed text, measured in degrees.
selectedselectionhighlightstringThe character string contained by the text object.
tagtypeuicontextmenuunitsMay be "normalized" or "graph".
userdataverticalalignmentvisiblexlimxlimincludeylimylimincludezlimzliminclude| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The image properties are:
__modified____myhandle__beingdeletedbusyactionbuttondownfcncdataThe data for the image. Each pixel of the image corresponds to an
element of cdata. The value of an element of cdata
specifies the row-index into the colormap of the axes object containing
the image. The color value found in the color map for the given index
determines the color of the pixel.
cdatamappingchildrenclimclimincludeclippingcreatefcndeletefcnhandlevisibilityhittestinterruptibleparentselectedselectionhighlighttagtypeuicontextmenuuserdatavisiblexdataTwo-element vector specifying the range of the x-coordinates for the image.
xlimxlimincludeydataTwo-element vector specifying the range of the y-coordinates for the image.
ylimyliminclude| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The patch properties are:
__modified____myhandle__alimalimincludealphadatamappingambientstrengthbackfacelightingbeingdeletedbusyactionbuttondownfcncdataData defining the patch object.
cdatamappingchildrenclimclimincludeclippingcreatefcndeletefcndiffusestrengthdisplaynameThe text of the legend entry corresponding to this line.
edgealphaedgecolorThe color of the line defining the patch. See section Colors.
edgelightingerasemodefacealphaA number in the range [0, 1] indicating the transparency of the patch.
facecolorThe fill color of the patch. See section Colors.
facelightingfacesfacevertexalphadatafacevertexcdatahandlevisibilityhittestinterpreterinterruptiblelinestyleSee section Line Styles.
linewidthSee section Line Styles.
markerSee section Marker Styles.
markeredgecolorSee section Marker Styles.
markerfacecolorSee section Marker Styles.
markersizeSee section Marker Styles.
normalmodeparentselectedselectionhighlightspecularcolorreflectancespecularexponentspecularstrengthtagtypeuicontextmenuuserdatavertexnormalsverticesvisiblexdataData defining the patch object.
xlimxlimincludeydataData defining the patch object.
ylimylimincludezdataData defining the patch object.
zlimzliminclude| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The surface properties are:
__modified____myhandle__alimalimincludealphadataalphadatamappingambientstrengthbackfacelightingbeingdeletedbusyactionbuttondownfcncdatacdatamappingcdatasourcechildrenclimclimincludeclippingcreatefcndeletefcndiffusestrengthdisplaynameThe text of the legend entry corresponding to this surface.
edgealphaedgecoloredgelightingerasemodefacealphafacecolorfacelightinghandlevisibilityhittestinterpreterinterruptiblelinestylelinewidthmarkermarkeredgecolormarkerfacecolormarkersizemeshstylenormalmodeparentselectedselectionhighlightspecularcolorreflectancespecularexponentspecularstrengthtagtypeuicontextmenuuserdatavertexnormalsvisiblexdataThe data determining the surface. The xdata and ydata
elements are vectors and zdata must be a matrix.
xdatasourcexlimxlimincludeydataThe data determining the surface. The xdata and ydata
elements are vectors and zdata must be a matrix.
ydatasourceylimylimincludezdataThe data determining the surface. The xdata and ydata
elements are vectors and zdata must be a matrix.
zdatasourcezlimzliminclude| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Find graphics object with specified property values.
The simplest form is
findobj (prop_name, prop_value) |
which returns the handles of all objects which have a property named prop_name that has the value prop_value. If multiple property/value pairs are specified then only objects meeting all of the conditions are returned.
The search can be limited to a particular set of objects and their descendants, by passing a handle or set of handles hlist as the first argument.
The depth of the object hierarchy to search can be limited with the
"-depth" argument. An example of searching only three generations
of children is:
findobj (hlist, "-depth", 3, prop_name, prop_value) |
Specifying a depth d of 0, limits the search to the set of objects
passed in hlist. A depth d of 0 is equivalent to the
"flat" argument.
A specified logical operator may be applied to the pairs of prop_name
and prop_value. The supported logical operators are:
"-and", "-or",
"-xor", "-not".
Objects may also be matched by comparing a regular expression to the
property values, where property values that match
regexp (prop_value, pattern) are returned.
Finally, objects may be matched by property name only by using the
"-property" option.
Implementation Note: The search only includes objects with visible
handles (HandleVisibility = "on"). See findall, to
search for all objects including hidden ones.
Find graphics object, including hidden ones, with specified property values.
The return value h is a list of handles to the found graphic objects.
findall performs the same search as findobj, but it
includes hidden objects (HandleVisibility = "off"). For full
documentation, see findobj.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Object properties have two classes of default values, factory defaults (the initial values) and user-defined defaults, which may override the factory defaults.
Although default values may be set for any object, they are set in
parent objects and apply to child objects, of the specified object type.
For example, setting the default color property of line
objects to "green", for the root object, will result in all
line objects inheriting the color "green" as the default
value.
set (0, "defaultlinecolor", "green"); |
sets the default line color for all objects. The rule for constructing the property name to set a default value is
default + object-type + property-name |
This rule can lead to some strange looking names, for example
defaultlinelinewidth" specifies the default linewidth
property for line objects.
The example above used the root figure object, 0, so the default property value will apply to all line objects. However, default values are hierarchical, so defaults set in a figure objects override those set in the root figure object. Likewise, defaults set in axes objects override those set in figure or root figure objects. For example,
subplot (2, 1, 1); set (0, "defaultlinecolor", "red"); set (1, "defaultlinecolor", "green"); set (gca (), "defaultlinecolor", "blue"); line (1:10, rand (1, 10)); subplot (2, 1, 2); line (1:10, rand (1, 10)); figure (2) line (1:10, rand (1, 10)); |
produces two figures. The line in first subplot window of the first figure is blue because it inherits its color from its parent axes object. The line in the second subplot window of the first figure is green because it inherits its color from its parent figure object. The line in the second figure window is red because it inherits its color from the global root figure parent object.
To remove a user-defined default setting, set the default property to
the value "remove". For example,
set (gca (), "defaultlinecolor", "remove"); |
removes the user-defined default line color setting from the current axes
object. To quickly remove all user-defined defaults use the reset
function.
Remove any defaults set for the handle h. The default figure
properties of "position", "units",
"windowstyle" and "paperunits" and the default axes
properties of "position" and "units" are not reset.
Getting the "default" property of an object returns a list of
user-defined defaults set for the object. For example,
get (gca (), "default"); |
returns a list of user-defined default values for the current axes object.
Factory default values are stored in the root figure object. The command
get (0, "factory"); |
returns a list of factory defaults.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 15.4.1 Colors | ||
| 15.4.2 Line Styles | ||
| 15.4.3 Marker Styles | ||
| 15.4.4 Callbacks | ||
| 15.4.5 Application-defined Data | ||
| 15.4.6 Object Groups | ||
| 15.4.7 Graphics Toolkits |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Colors may be specified as RGB triplets with values ranging from zero to
one, or by name. Recognized color names include "blue",
"black", "cyan", "green", "magenta",
"red", "white", and "yellow".
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Line styles are specified by the following properties:
linestyleMay be one of
"-"Solid line. [default]
"--"Dashed line.
":"Dotted line.
"-."A dash-dot line.
"none"No line. Points will still be marked using the current Marker Style.
linewidthA number specifying the width of the line. The default is 1. A value of 2 is twice as wide as the default, etc.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Marker styles are specified by the following properties:
markerA character indicating a plot marker to be place at each data point, or
"none", meaning no markers should be displayed.
markeredgecolorThe color of the edge around the marker, or "auto", meaning that
the edge color is the same as the face color. See section Colors.
markerfacecolorThe color of the marker, or "none" to indicate that the marker
should not be filled. See section Colors.
markersizeA number specifying the size of the marker. The default is 1. A value of 2 is twice as large as the default, etc.
The colstyle function will parse a plot-style specification
and will return the color, line, and marker values that would result.
Parse linespec and return the line style, color, and markers given. In the case of an error, the string msg will return the text of the error.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Callback functions can be associated with graphics objects and triggered after certain events occur. The basic structure of all callback function is
function mycallback (src, data) … endfunction |
where src gives a handle to the source of the callback, and
code gives some event specific data. This can then be associated
with an object either at the objects creation or later with the
set function. For example,
plot (x, "DeleteFcn", @(s, e) disp ("Window Deleted"))
|
where at the moment that the plot is deleted, the message "Window Deleted" will be displayed.
Additional user arguments can be passed to callback functions, and will be passed after the 2 default arguments. For example:
plot (x, "DeleteFcn", {@mycallback, "1"})
…
function mycallback (src, data, a1)
fprintf ("Closing plot %d\n", a1);
endfunction
|
The basic callback functions that are available for all graphics objects are
CreateFcn later with
the set function will never be executed.
The object and figure that the event occurred in that resulted in the
callback being called can be found with the gcbo and gcbf
functions.
Return a handle to the object whose callback is currently executing.
If no callback is executing, this function returns the empty matrix. This
handle is obtained from the root object property "CallbackObject".
When called with a second output argument, return the handle of the figure containing the object whose callback is currently executing. If no callback is executing the second output is also set to the empty matrix.
Return a handle to the figure containing the object whose callback is currently executing.
If no callback is executing, this function returns the empty matrix. The
handle returned by this function is the same as the second output argument
of gcbo.
Callbacks can equally be added to properties with the addlistener
function described below.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave has a provision for attaching application-defined data to a graphics handle. The data can be anything which is meaningful to the application, and will be completely ignored by Octave.
Set the named application data to value for the object(s) with handle(s) h. If the application data with the specified name does not exist, it is created.
Return the value for named application data for the object(s) with handle(s) h.
getappdata(h) returns a structure, appdata, whose fields
correspond to the appdata properties.
Delete the named application data for the object(s) with handle(s) h.
Return true if the named application data, name, exists for the object with handle h.
See also: getappdata, setappdata, rmappdata.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A number of Octave high level plot functions return groups of other
graphics objects or they return graphics objects that have their
properties linked in such a way that changes to one of the properties
results in changes in the others. A graphic object that groups other
objects is an hggroup
Create handle graphics group object with axes parent hax.
If no parent is specified, the group is created in the current axes.
Multiple property/value pairs may be specified for the hggroup, but they must appear in pairs.
The optional return value h is a graphics handle to the created hggroup object.
Programming Note: An hggroup is a way to group base graphics objects such
as line objects or patch objects into a single unit which can react
appropriately. For example, the individual lines of a contour plot are
collected into a single hggroup so that they can be made visible/invisible
with a single command, set (hg_handle, "visible", "off").
See also: addproperty, addlistener.
For example a simple use of a hggroup might be
x = 0:0.1:10; hg = hggroup (); plot (x, sin (x), "color", [1, 0, 0], "parent", hg); hold on plot (x, cos (x), "color", [0, 1, 0], "parent", hg); set (hg, "visible", "off"); |
which groups the two plots into a single object and controls their
visibility directly. The default properties of an hggroup are
the same as the set of common properties for the other graphics
objects. Additional properties can be added with the addproperty
function.
Create a new property named name in graphics object h. type determines the type of the property to create. args usually contains the default value of the property, but additional arguments might be given, depending on the type of the property.
The supported property types are:
stringA string property. arg contains the default string value.
anyAn un-typed property. This kind of property can hold any octave value. args contains the default value.
radioA string property with a limited set of accepted values. The first argument must be a string with all accepted values separated by a vertical bar (’|’). The default value can be marked by enclosing it with a ’{’ ’}’ pair. The default value may also be given as an optional second string argument.
booleanA boolean property. This property type is equivalent to a radio property with "on|off" as accepted values. arg contains the default property value.
doubleA scalar double property. arg contains the default value.
handleA handle property. This kind of property holds the handle of a graphics object. arg contains the default handle value. When no default value is given, the property is initialized to the empty matrix.
dataA data (matrix) property. arg contains the default data value. When no default value is given, the data is initialized to the empty matrix.
colorA color property. arg contains the default color value. When no default color is given, the property is set to black. An optional second string argument may be given to specify an additional set of accepted string values (like a radio property).
type may also be the concatenation of a core object type and a valid property name for that object type. The property created then has the same characteristics as the referenced property (type, possible values, hidden state…). This allows to clone an existing property into the graphics object h.
Examples:
addproperty ("my_property", gcf, "string", "a string value");
addproperty ("my_radio", gcf, "radio", "val_1|val_2|{val_3}");
addproperty ("my_style", gcf, "linelinestyle", "--");
|
See also: addlistener, hggroup.
Once a property in added to an hggroup, it is not linked to any
other property of either the children of the group, or any other
graphics object. Add so to control the way in which this newly added
property is used, the addlistener function is used to define a
callback function that is executed when the property is altered.
Register fcn as listener for the property prop of the graphics object h. Property listeners are executed (in order of registration) when the property is set. The new value is already available when the listeners are executed.
prop must be a string naming a valid property in h.
fcn can be a function handle, a string or a cell array whose first element is a function handle. If fcn is a function handle, the corresponding function should accept at least 2 arguments, that will be set to the object handle and the empty matrix respectively. If fcn is a string, it must be any valid octave expression. If fcn is a cell array, the first element must be a function handle with the same signature as described above. The next elements of the cell array are passed as additional arguments to the function.
Example:
function my_listener (h, dummy, p1)
fprintf ("my_listener called with p1=%s\n", p1);
endfunction
addlistener (gcf, "position", {@my_listener, "my string"})
|
See also: addproperty, hggroup.
Remove the registration of fcn as a listener for the property
prop of the graphics object h. The function fcn must
be the same variable (not just the same value), as was passed to the
original call to addlistener.
If fcn is not defined then all listener functions of prop are removed.
Example:
function my_listener (h, dummy, p1)
fprintf ("my_listener called with p1=%s\n", p1);
endfunction
c = {@my_listener, "my string"};
addlistener (gcf, "position", c);
dellistener (gcf, "position", c);
|
An example of the use of these two functions might be
x = 0:0.1:10;
hg = hggroup ();
h = plot (x, sin (x), "color", [1, 0, 0], "parent", hg);
addproperty ("linestyle", hg, "linelinestyle", get (h, "linestyle"));
addlistener (hg, "linestyle", @update_props);
hold on
plot (x, cos (x), "color", [0, 1, 0], "parent", hg);
function update_props (h, d)
set (get (h, "children"), "linestyle", get (h, "linestyle"));
endfunction
|
that adds a linestyle property to the hggroup and
propagating any changes its value to the children of the group. The
linkprop function can be used to simplify the above to be
x = 0:0.1:10;
hg = hggroup ();
h1 = plot (x, sin (x), "color", [1, 0, 0], "parent", hg);
addproperty ("linestyle", hg, "linelinestyle", get (h, "linestyle"));
hold on
h2 = plot (x, cos (x), "color", [0, 1, 0], "parent", hg);
hlink = linkprop ([hg, h1, h2], "color");
|
Link graphics object properties, such that a change in one is propagated to the others.
prop can be a string for a single property, or a cell array of strings for multiple properties. h is an array of graphics handles which will have their properties linked.
An example of the use of linkprop is
x = 0:0.1:10;
subplot (1,2,1);
h1 = plot (x, sin (x));
subplot (1,2,2);
h2 = plot (x, cos (x));
hlink = linkprop ([h1, h2], {"color","linestyle"});
set (h1, "color", "green");
set (h2, "linestyle", "--");
|
These capabilities are used in a number of basic graphics objects.
The hggroup objects created by the functions of Octave contain
one or more graphics object and are used to:
For example the stem function creates a stem series where each
hggroup of the stem series contains two line objects representing
the body and head of the stem. The ydata property of the
hggroup of the stem series represents the head of the stem,
whereas the body of the stem is between the baseline and this value. For
example
h = stem (1:4) get (h, "xdata") ⇒ [ 1 2 3 4]' get (get (h, "children")(1), "xdata") ⇒ [ 1 1 NaN 2 2 NaN 3 3 NaN 4 4 NaN]' |
shows the difference between the xdata of the hggroup
of a stem series object and the underlying line.
The basic properties of such group objects is that they consist of one
or more linked hggroup, and that changes in certain properties of
these groups are propagated to other members of the group. Whereas,
certain properties of the members of the group only apply to the current
member.
In addition the members of the group can also be linked to other
graphics objects through callback functions. For example the baseline of
the bar or stem functions is a line object, whose length
and position are automatically adjusted, based on changes to the
corresponding hggroup elements.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
All of the group objects contain data source parameters. There are
string parameters that contain an expression that is evaluated to update
the relevant data property of the group when the refreshdata
function is called.
Evaluate any ‘datasource’ properties of the current figure and update the plot if the corresponding data has changed.
If the first argument h is a list of graphic handles, then operate
on these objects rather than the current figure returned by gcf.
The optional second argument workspace can take the following values:
"base"Evaluate the datasource properties in the base workspace. (default).
"caller"Evaluate the datasource properties in the workspace of the function
that called refreshdata.
An example of the use of refreshdata is:
x = 0:0.1:10; y = sin (x); plot (x, y, "ydatasource", "y"); for i = 1 : 100 pause (0.1); y = sin (x + 0.1*i); refreshdata (); endfor |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Area series objects are created by the area function. Each of the
hggroup elements contains a single patch object. The properties
of the area series are
basevalueThe value where the base of the area plot is drawn.
linewidthlinestyleThe line width and style of the edge of the patch objects making up the areas. See section Line Styles.
edgecolorfacecolorThe line and fill color of the patch objects making up the areas. See section Colors.
xdataydataThe x and y coordinates of the original columns of the data passed to
area prior to the cumulative summation used in the area
function.
xdatasourceydatasourceData source variables.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Bar series objects are created by the bar or barh
functions. Each hggroup element contains a single patch object.
The properties of the bar series are
showbaselinebaselinebasevalueThe property showbaseline flags whether the baseline of the bar
series is displayed (default is "on"). The handle of the graphics
object representing the baseline is given by the baseline property and
the y-value of the baseline by the basevalue property.
Changes to any of these properties are propagated to the other members of the bar series and to the baseline itself. Equally, changes in the properties of the base line itself are propagated to the members of the corresponding bar series.
barwidthbarlayouthorizontalThe property barwidth is the width of the bar corresponding to
the width variable passed to bar or barh. Whether the
bar series is "grouped" or "stacked" is determined by the
barlayout property and whether the bars are horizontal or
vertical by the horizontal property.
Changes to any of these property are propagated to the other members of the bar series.
linewidthlinestyleThe line width and style of the edge of the patch objects making up the bars. See section Line Styles.
edgecolorfacecolorThe line and fill color of the patch objects making up the bars. See section Colors.
xdataThe nominal x positions of the bars. Changes in this property and propagated to the other members of the bar series.
ydataThe y value of the bars in the hggroup.
xdatasourceydatasourceData source variables.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Contour group objects are created by the contour, contourf
and contour3 functions. The are equally one of the handles returned
by the surfc and meshc functions. The properties of the contour
group are
contourmatrixA read only property that contains the data return by contourc used to
create the contours of the plot.
fillA radio property that can have the values "on" or "off" that
flags whether the contours to plot are to be filled.
zlevelmodezlevelThe radio property zlevelmode can have the values "none",
"auto", or "manual". When its value is "none" there is
no z component to the plotted contours. When its value is "auto" the z
value of the plotted contours is at the same value as the contour itself. If
the value is "manual", then the z value at which to plot the contour is
determined by the zlevel property.
levellistmodelevellistlevelstepmodelevelstepIf levellistmode is "manual", then the levels at which to plot
the contours is determined by levellist. If levellistmode is set
to "auto", then the distance between contours is determined by
levelstep. If both levellistmode and levelstepmode are
set to "auto", then there are assumed to be 10 equal spaced contours.
textlistmodetextlisttextstepmodetextstepIf textlistmode is "manual", then the labeled contours
is determined by textlist. If textlistmode is set to
"auto", then the distance between labeled contours is determined by
textstep. If both textlistmode and textstepmode
are set to "auto", then there are assumed to be 10 equal spaced
labeled contours.
showtextFlag whether the contour labels are shown or not.
labelspacingThe distance between labels on a single contour in points.
linewidthlinestylelinecolorThe properties of the contour lines. The properties linewidth and
linestyle are similar to the corresponding properties for lines. The
property linecolor is a color property (see section Colors), that can also
have the values of "none" or "auto". If linecolor is
"none", then no contour line is drawn. If linecolor is
"auto" then the line color is determined by the colormap.
xdataydatazdataThe original x, y, and z data of the contour lines.
xdatasourceydatasourcezdatasourceData source variables.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Error bar series are created by the errorbar function. Each
hggroup element contains two line objects representing the data and
the errorbars separately. The properties of the error bar series are
colorThe RGB color or color name of the line objects of the error bars. See section Colors.
linewidthlinestyleThe line width and style of the line objects of the error bars. See section Line Styles.
markermarkeredgecolormarkerfacecolormarkersizeThe line and fill color of the markers on the error bars. See section Colors.
xdataydataldataudataxldataxudataThe original x, y, l, u, xl, xu data of the error bars.
xdatasourceydatasourceldatasourceudatasourcexldatasourcexudatasourceData source variables.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Line series objects are created by the plot and plot3
functions and are of the type line. The properties of the
line series with the ability to add data sources.
colorThe RGB color or color name of the line objects. See section Colors.
linewidthlinestyleThe line width and style of the line objects. See section Line Styles.
markermarkeredgecolormarkerfacecolormarkersizeThe line and fill color of the markers. See section Colors.
xdataydatazdataThe original x, y and z data.
xdatasourceydatasourcezdatasourceData source variables.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Quiver series objects are created by the quiver or quiver3
functions. Each hggroup element of the series contains three line
objects as children representing the body and head of the arrow,
together with a marker as the point of origin of the arrows. The
properties of the quiver series are
autoscaleautoscalefactorFlag whether the length of the arrows is scaled or defined directly from
the u, v and w data. If the arrow length is flagged
as being scaled by the autoscale property, then the length of the
autoscaled arrow is controlled by the autoscalefactor.
maxheadsizeThis property controls the size of the head of the arrows in the quiver series. The default value is 0.2.
showarrowheadFlag whether the arrow heads are displayed in the quiver plot.
colorThe RGB color or color name of the line objects of the quiver. See section Colors.
linewidthlinestyleThe line width and style of the line objects of the quiver. See section Line Styles.
markermarkerfacecolormarkersizeThe line and fill color of the marker objects at the original of the arrows. See section Colors.
xdataydatazdataThe origins of the values of the vector field.
udatavdatawdataThe values of the vector field to plot.
xdatasourceydatasourcezdatasourceudatasourcevdatasourcewdatasourceData source variables.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Scatter series objects are created by the scatter or scatter3
functions. A single hggroup element contains as many children as there are
points in the scatter plot, with each child representing one of the points.
The properties of the stem series are
linewidthThe line width of the line objects of the points. See section Line Styles.
markermarkeredgecolormarkerfacecolorThe line and fill color of the markers of the points. See section Colors.
xdataydatazdataThe original x, y and z data of the stems.
cdataThe color data for the points of the plot. Each point can have a separate color, or a unique color can be specified.
sizedataThe size data for the points of the plot. Each point can its own size or a unique size can be specified.
xdatasourceydatasourcezdatasourcecdatasourcesizedatasourceData source variables.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Stair series objects are created by the stair function. Each
hggroup element of the series contains a single line object as a
child representing the stair. The properties of the stair series are
colorThe RGB color or color name of the line objects of the stairs. See section Colors.
linewidthlinestyleThe line width and style of the line objects of the stairs. See section Line Styles.
markermarkeredgecolormarkerfacecolormarkersizeThe line and fill color of the markers on the stairs. See section Colors.
xdataydataThe original x and y data of the stairs.
xdatasourceydatasourceData source variables.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Stem series objects are created by the stem or stem3
functions. Each hggroup element contains a single line object
as a child representing the stems. The properties of the stem series
are
showbaselinebaselinebasevalueThe property showbaseline flags whether the baseline of the
stem series is displayed (default is "on"). The handle of the graphics
object representing the baseline is given by the baseline
property and the y-value (or z-value for stem3) of the baseline
by the basevalue property.
Changes to any of these property are propagated to the other members of the stem series and to the baseline itself. Equally changes in the properties of the base line itself are propagated to the members of the corresponding stem series.
colorThe RGB color or color name of the line objects of the stems. See section Colors.
linewidthlinestyleThe line width and style of the line objects of the stems. See section Line Styles.
markermarkeredgecolormarkerfacecolormarkersizeThe line and fill color of the markers on the stems. See section Colors.
xdataydatazdataThe original x, y and z data of the stems.
xdatasourceydatasourcezdatasourceData source variables.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Surface group objects are created by the surf or mesh
functions, but are equally one of the handles returned by the surfc
or meshc functions. The surface group is of the type surface.
The properties of the surface group are
edgecolorfacecolorThe RGB color or color name of the edges or faces of the surface. See section Colors.
linewidthlinestyleThe line width and style of the lines on the surface. See section Line Styles.
markermarkeredgecolormarkerfacecolormarkersizeThe line and fill color of the markers on the surface. See section Colors.
xdataydatazdatacdataThe original x, y, z and c data.
xdatasourceydatasourcezdatasourcecdatasourceData source variables.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Query or set the default graphics toolkit which is assigned to new figures.
With no inputs, return the current default graphics toolkit. If the input is a list of figure graphic handles, hlist, then return the name of the graphics toolkit in use for each figure.
When called with a single input name set the default graphics toolkit
to name. If the toolkit is not already loaded, it is initialized by
calling the function __init_name__. If the first input
is a list of figure handles, hlist, then the graphics toolkit is set
to name for these figures only.
See also: available_graphics_toolkits.
Return a cell array of registered graphics toolkits.
See also: graphics_toolkit, register_graphics_toolkit.
Return a cell array of the currently loaded graphics toolkits.
See also: available_graphics_toolkits.
List toolkit as an available graphics toolkit.
See also: available_graphics_toolkits.
| 15.4.7.1 Customizing Toolkit Behavior |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The specific behavior of the backend toolkit may be modified using the following utility functions. Note: Not all functions apply to every graphics toolkit.
Query or set the name of the program invoked by the plot command
when the graphics toolkit is set to "gnuplot". Additional arguments to
pass to the external plotting program may also be given.
The default value is "gnuplot" with no additional arguments.
See section Installing Octave.
See also: graphics_toolkit.
Query or set the GUI mode for the current graphics toolkit. The mode argument can be one of the following strings:
"2d"Allows panning and zooming of current axes.
"3d"Allows rotating and zooming of current axes.
"none"Mouse inputs have no effect.
This function is currently implemented only for the FLTK graphics toolkit.
See also: mouse_wheel_zoom.
Query or set the mouse wheel zoom factor.
The zoom factor is a number in the range (0,1) which is the percentage of the
current axis limits that will be used when zooming. For example, if the
current x-axis limits are [0, 50] and mouse_wheel_zoom is 0.4 (40%),
then a zoom operation will change the limits by 20.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
This function is currently implemented only for the FLTK graphics toolkit.
See also: gui_mode.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There are a number of functions available for checking to see if the elements of a matrix meet some condition, and for rearranging the elements of a matrix. For example, Octave can easily tell you if all the elements of a matrix are finite, or are less than some specified value. Octave can also rotate the elements, extract the upper- or lower-triangular parts, or sort the columns of a matrix.
| 16.1 Finding Elements and Checking Conditions | ||
| 16.2 Rearranging Matrices | ||
| 16.3 Special Utility Matrices | ||
| 16.4 Famous Matrices |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The functions any and all are useful for determining
whether any or all of the elements of a matrix satisfy some condition.
The find function is also useful in determining which elements of
a matrix meet a specified condition.
For a vector argument, return true (logical 1) if any element of the vector is non-zero.
For a matrix argument, return a row vector of logical ones and zeros with each element indicating whether any of the elements of the corresponding column of the matrix are non-zero. For example:
any (eye (2, 4)) ⇒ [ 1, 1, 0, 0 ] |
If the optional argument dim is supplied, work along dimension dim. For example:
any (eye (2, 4), 2) ⇒ [ 1; 1 ] |
See also: all.
For a vector argument, return true (logical 1) if all elements of the vector are non-zero.
For a matrix argument, return a row vector of logical ones and zeros with each element indicating whether all of the elements of the corresponding column of the matrix are non-zero. For example:
all ([2, 3; 1, 0]))
⇒ [ 1, 0 ]
|
If the optional argument dim is supplied, work along dimension dim.
See also: any.
Since the comparison operators (see section Comparison Operators) return matrices of ones and zeros, it is easy to test a matrix for many things, not just whether the elements are nonzero. For example,
all (all (rand (5) < 0.9))
⇒ 0
|
tests a random 5 by 5 matrix to see if all of its elements are less than 0.9.
Note that in conditional contexts (like the test clause of if and
while statements) Octave treats the test as if you had typed
all (all (condition)).
Return the exclusive or of the entries of x and y.
For boolean expressions x and y,
xor (x, y) is true if and only if one of x or
y is true. Otherwise, for x and y both true or both
false, xor returns false.
The truth table for the xor operation is
| x | y | z | ||
| 0 | 0 | 0 | ||
| 1 | 0 | 1 | ||
| 0 | 1 | 1 | ||
| 1 | 1 | 0 |
If x is a vector of length n, diff (x) is the
vector of first differences
x(2) - x(1), …, x(n) - x(n-1).
If x is a matrix, diff (x) is the matrix of column
differences along the first non-singleton dimension.
The second argument is optional. If supplied, diff (x,
k), where k is a non-negative integer, returns the
k-th differences. It is possible that k is larger than
the first non-singleton dimension of the matrix. In this case,
diff continues to take the differences along the next
non-singleton dimension.
The dimension along which to take the difference can be explicitly
stated with the optional variable dim. In this case the
k-th order differences are calculated along this dimension.
In the case where k exceeds size (x, dim)
an empty matrix is returned.
Return a logical array which is true where the elements of x are are infinite and false where they are not. For example:
isinf ([13, Inf, NA, NaN])
⇒ [ 0, 1, 0, 0 ]
|
Return a logical array which is true where the elements of x are NaN values and false where they are not. NA values are also considered NaN values. For example:
isnan ([13, Inf, NA, NaN])
⇒ [ 0, 0, 1, 1 ]
|
Return a logical array which is true where the elements of x are finite values and false where they are not. For example:
finite ([13, Inf, NA, NaN])
⇒ [ 1, 0, 0, 0 ]
|
Determine if all input arguments are either scalar or of common size. If so, err is zero, and yi is a matrix of the common size with all entries equal to xi if this is a scalar or xi otherwise. If the inputs cannot be brought to a common size, err is 1, and yi is xi. For example:
[errorcode, a, b] = common_size ([1 2; 3 4], 5)
⇒ errorcode = 0
⇒ a = [ 1, 2; 3, 4 ]
⇒ b = [ 5, 5; 5, 5 ]
|
This is useful for implementing functions where arguments can either be scalars or of common size.
Return a vector of indices of nonzero elements of a matrix, as a row if x is a row vector or as a column otherwise. To obtain a single index for each matrix element, Octave pretends that the columns of a matrix form one long vector (like Fortran arrays are stored). For example:
find (eye (2)) ⇒ [ 1; 4 ] |
If two outputs are requested, find returns the row and column
indices of nonzero elements of a matrix. For example:
[i, j] = find (2 * eye (2))
⇒ i = [ 1; 2 ]
⇒ j = [ 1; 2 ]
|
If three outputs are requested, find also returns a vector
containing the nonzero values. For example:
[i, j, v] = find (3 * eye (2))
⇒ i = [ 1; 2 ]
⇒ j = [ 1; 2 ]
⇒ v = [ 3; 3 ]
|
If two inputs are given, n indicates the maximum number of elements to find from the beginning of the matrix or vector.
If three inputs are given, direction should be one of
"first" or "last", requesting only the first or last
n indices, respectively. However, the indices are always returned in
ascending order.
Note that this function is particularly useful for sparse matrices, as it extracts the non-zero elements as vectors, which can then be used to create the original matrix. For example:
sz = size (a); [i, j, v] = find (a); b = sparse (i, j, v, sz(1), sz(2)); |
See also: nonzeros.
Lookup values in a sorted table. Usually used as a prelude to interpolation.
If table is increasing and idx = lookup (table, y), then
table(idx(i)) <= y(i) < table(idx(i+1)) for all y(i)
within the table. If y(i) < table(1) then
idx(i) is 0. If y(i) >= table(end) or isnan (y(i)) then
idx(i) is n.
If the table is decreasing, then the tests are reversed. For non-strictly monotonic tables, empty intervals are always skipped. The result is undefined if table is not monotonic, or if table contains a NaN.
The complexity of the lookup is O(M*log(N)) where N is the size of table and M is the size of y. In the special case when y is also sorted, the complexity is O(min(M*log(N),M+N)).
table and y can also be cell arrays of strings (or y can be a single string). In this case, string lookup is performed using lexicographical comparison.
If opts is specified, it must be a string with letters indicating additional options.
mtable(idx(i)) == val(i) if val(i)
occurs in table; otherwise, idx(i) is zero.
bidx(i) is a logical 1 or 0, indicating whether
val(i) is contained in table or not.
lFor numeric lookups the leftmost subinterval shall be extended to infinity (i.e., all indices at least 1)
rFor numeric lookups the rightmost subinterval shall be extended to infinity (i.e., all indices at most n-1).
If you wish to check if a variable exists at all, instead of properties its elements may have, consult Status of Variables.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Return a copy of x with the order of the columns reversed. In other words, x is flipped left-to-right about a vertical axis. For example:
fliplr ([1, 2; 3, 4])
⇒ 2 1
4 3
|
Note that fliplr only works with 2-D arrays. To flip N-D arrays
use flipdim instead.
Return a copy of x with the order of the rows reversed. In other words, x is flipped upside-down about a horizontal axis. For example:
flipud ([1, 2; 3, 4])
⇒ 3 4
1 2
|
Note that flipud only works with 2-D arrays. To flip N-D arrays
use flipdim instead.
Return a copy of x flipped about the dimension dim. dim defaults to the first non-singleton dimension. For example:
flipdim ([1, 2; 3, 4], 2)
⇒ 2 1
4 3
|
Return a copy of A with the elements rotated counterclockwise in 90-degree increments. The second argument is optional, and specifies how many 90-degree rotations are to be applied (the default value is 1). Negative values of k rotate the matrix in a clockwise direction. For example,
rot90 ([1, 2; 3, 4], -1)
⇒ 3 1
4 2
|
rotates the given matrix clockwise by 90 degrees. The following are all equivalent statements:
rot90 ([1, 2; 3, 4], -1) rot90 ([1, 2; 3, 4], 3) rot90 ([1, 2; 3, 4], 7) |
Note that rot90 only works with 2-D arrays. To rotate N-D arrays
use rotdim instead.
Return a copy of x with the elements rotated counterclockwise in 90-degree increments. The second argument n is optional, and specifies how many 90-degree rotations are to be applied (the default value is 1). The third argument is also optional and defines the plane of the rotation. If present, plane is a two element vector containing two different valid dimensions of the matrix. When plane is not given the first two non-singleton dimensions are used.
Negative values of n rotate the matrix in a clockwise direction. For example,
rotdim ([1, 2; 3, 4], -1, [1, 2])
⇒ 3 1
4 2
|
rotates the given matrix clockwise by 90 degrees. The following are all equivalent statements:
rotdim ([1, 2; 3, 4], -1, [1, 2]) rotdim ([1, 2; 3, 4], 3, [1, 2]) rotdim ([1, 2; 3, 4], 7, [1, 2]) |
Return the concatenation of N-D array objects, array1, array2, …, arrayN along dimension dim.
A = ones (2, 2);
B = zeros (2, 2);
cat (2, A, B)
⇒ 1 1 0 0
1 1 0 0
|
Alternatively, we can concatenate A and B along the second dimension in the following way:
[A, B] |
dim can be larger than the dimensions of the N-D array objects and the result will thus have dim dimensions as the following example shows:
cat (4, ones (2, 2), zeros (2, 2))
⇒ ans(:,:,1,1) =
1 1
1 1
ans(:,:,1,2) =
0 0
0 0
|
Return the horizontal concatenation of N-D array objects, array1, array2, …, arrayN along dimension 2.
Arrays may also be concatenated horizontally using the syntax for creating new matrices. For example:
hcat = [ array1, array2, … ] |
Return the vertical concatenation of N-D array objects, array1, array2, …, arrayN along dimension 1.
Arrays may also be concatenated vertically using the syntax for creating new matrices. For example:
vcat = [ array1; array2; … ] |
Return the generalized transpose for an N-D array object A.
The permutation vector perm must contain the elements
1:ndims (A) (in any order, but each element must appear only once).
See also: ipermute.
The inverse of the permute function. The expression
ipermute (permute (A, perm), perm) |
returns the original array A.
See also: permute.
Return a matrix with the specified dimensions (m, n, …) whose elements are taken from the matrix A. The elements of the matrix are accessed in column-major order (like Fortran arrays are stored).
The following code demonstrates reshaping a 1x4 row vector into a 2x2 square matrix.
reshape ([1, 2, 3, 4], 2, 2)
⇒ 1 3
2 4
|
Note that the total number of elements in the original
matrix (prod (size (A))) must match the total number of elements
in the new matrix (prod ([m n …])).
A single dimension of the return matrix may be left unspecified and Octave will determine its size automatically. An empty matrix ([]) is used to flag the unspecified dimension.
Resize x cutting off elements as necessary.
In the result, element with certain indices is equal to the corresponding element of x if the indices are within the bounds of x; otherwise, the element is set to zero.
In other words, the statement
y = resize (x, dv) |
is equivalent to the following code:
y = zeros (dv, class (x));
sz = min (dv, size (x));
for i = 1:length (sz)
idx{i} = 1:sz(i);
endfor
y(idx{:}) = x(idx{:});
|
but is performed more efficiently.
If only m is supplied, and it is a scalar, the dimension of the result is m-by-m. If m, n, … are all scalars, then the dimensions of the result are m-by-n-by-…. If given a vector as input, then the dimensions of the result are given by the elements of that vector.
An object can be resized to more dimensions than it has; in such case the missing dimensions are assumed to be 1. Resizing an object to fewer dimensions is not possible.
Circularly shift the values of the array x. n must be a vector of integers no longer than the number of dimensions in x. The values of n can be either positive or negative, which determines the direction in which the values or x are shifted. If an element of n is zero, then the corresponding dimension of x will not be shifted. For example:
x = [1, 2, 3; 4, 5, 6; 7, 8, 9];
circshift (x, 1)
⇒ 7, 8, 9
1, 2, 3
4, 5, 6
circshift (x, -2)
⇒ 7, 8, 9
1, 2, 3
4, 5, 6
circshift (x, [0,1])
⇒ 3, 1, 2
6, 4, 5
9, 7, 8
|
See also: permute, ipermute, shiftdim.
If x is a vector, perform a circular shift of length b of the elements of x.
If x is a matrix, do the same for each column of x. If the optional dim argument is given, operate along this dimension.
Shift the dimensions of x by n, where n must be an integer scalar. When n is positive, the dimensions of x are shifted to the left, with the leading dimensions circulated to the end. If n is negative, then the dimensions of x are shifted to the right, with n leading singleton dimensions added.
Called with a single argument, shiftdim, removes the leading
singleton dimensions, returning the number of dimensions removed
in the second output argument ns.
For example:
x = ones (1, 2, 3); size (shiftdim (x, -1)) ⇒ [1, 1, 2, 3] size (shiftdim (x, 1)) ⇒ [2, 3] [b, ns] = shiftdim (x) ⇒ b = [1, 1, 1; 1, 1, 1] ⇒ ns = 1 |
See also: reshape, permute, ipermute, circshift, squeeze.
Return a copy of x with the elements arranged in increasing
order. For matrices, sort orders the elements within columns
For example:
sort ([1, 2; 2, 3; 3, 1])
⇒ 1 1
2 2
3 3
|
If the optional argument dim is given, then the matrix is sorted
along the dimension defined by dim. The optional argument mode
defines the order in which the values will be sorted. Valid values of
mode are "ascend" or "descend".
The sort function may also be used to produce a matrix
containing the original row indices of the elements in the sorted
matrix. For example:
[s, i] = sort ([1, 2; 2, 3; 3, 1])
⇒ s = 1 1
2 2
3 3
⇒ i = 1 3
2 1
3 2
|
For equal elements, the indices are such that equal elements are listed in the order in which they appeared in the original list.
Sorting of complex entries is done first by magnitude (abs (z))
and for any ties by phase angle (angle (z)). For example:
sort ([1+i; 1; 1-i])
⇒ 1 + 0i
1 - 1i
1 + 1i
|
NaN values are treated as being greater than any other value and are sorted to the end of the list.
The sort function may also be used to sort strings and cell arrays
of strings, in which case ASCII dictionary order (uppercase ’A’ precedes
lowercase ’a’) of the strings is used.
The algorithm used in sort is optimized for the sorting of partially
ordered lists.
Sort the rows of the matrix A according to the order of the columns specified in c. If c is omitted, a lexicographical sort is used. By default ascending order is used however if elements of c are negative then the corresponding column is sorted in descending order.
See also: sort.
Return true if the array is sorted according to mode, which
may be either "ascending", "descending", or
"either". By default, mode is "ascending". NaNs
are treated in the same manner as sort.
If the optional argument "rows" is supplied, check whether
the array is sorted by rows as output by the function sortrows
(with no options).
This function does not support sparse matrices.
Select the n-th smallest element of a vector, using the ordering defined by
sort. In other words, the result is equivalent to
sort(x)(n).
n can also be a contiguous range, either ascending l:u
or descending u:-1:l, in which case a range of elements is returned.
If x is an array, nth_element operates along the dimension
defined by dim, or the first non-singleton dimension if dim is
not given.
nth_element encapsulates the C++ standard library algorithms nth_element and
partial_sort. On average, the complexity of the operation is O(M*log(K)),
where M = size (x, dim) and
K = length (n).
This function is intended for cases where the ratio K/M is small; otherwise,
it may be better to use sort.
Return a new matrix formed by extracting the lower (tril)
or upper (triu) triangular part of the matrix A, and
setting all other elements to zero. The second argument is optional,
and specifies how many diagonals above or below the main diagonal should
also be set to zero.
The default value of k is zero, so that triu and
tril normally include the main diagonal as part of the result.
If the value of k is nonzero integer, the selection of elements starts at an offset of k diagonals above or below the main diagonal; above for positive k and below for negative k.
The absolute value of k must not be greater than the number of sub-diagonals or super-diagonals.
For example:
tril (ones (3), -1)
⇒ 0 0 0
1 0 0
1 1 0
|
and
tril (ones (3), 1)
⇒ 1 1 0
1 1 1
1 1 1
|
If the option "pack" is given as third argument, the extracted
elements are not inserted into a matrix, but rather stacked column-wise one
above other.
See also: diag.
Return the vector obtained by stacking the columns of the matrix x
one above the other. Without dim this is equivalent to
x(:). If dim is supplied, the dimensions of v
are set to dim with all elements along the last dimension.
This is equivalent to shiftdim (x(:), 1-dim).
Return the vector obtained by eliminating all supradiagonal elements of the square matrix x and stacking the result one column above the other. This has uses in matrix calculus where the underlying matrix is symmetric and it would be pointless to keep values above the main diagonal.
See also: vec.
Prepend the scalar value c to the vector x until it is of length l. If c is not given, a value of 0 is used.
If length (x) > l, elements from the beginning of
x are removed until a vector of length l is obtained.
If x is a matrix, elements are prepended or removed from each row.
If the optional argument dim is given, operate along this dimension.
Append the scalar value c to the vector x until it is of length l. If c is not given, a value of 0 is used.
If length (x) > l, elements from the end of
x are removed until a vector of length l is obtained.
If x is a matrix, elements are appended or removed from each row.
If the optional argument dim is given, operate along this dimension.
Return a diagonal matrix with vector v on diagonal k. The second argument is optional. If it is positive, the vector is placed on the k-th super-diagonal. If it is negative, it is placed on the -k-th sub-diagonal. The default value of k is 0, and the vector is placed on the main diagonal. For example:
diag ([1, 2, 3], 1)
⇒ 0 1 0 0
0 0 2 0
0 0 0 3
0 0 0 0
|
The 3-input form returns a diagonal matrix with vector v on the main diagonal and the resulting matrix being of size m rows x n columns.
Given a matrix argument, instead of a vector, diag extracts the
k-th diagonal of the matrix.
Build a block diagonal matrix from A, B, C, … All the arguments must be numeric and are two-dimensional matrices or scalars. If any argument is of type sparse, the output will also be sparse.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Return an identity matrix. If invoked with a single scalar argument n,
return a square NxN identity matrix. If
supplied two scalar arguments (m, n), eye takes them to be
the number of rows and columns. If given a vector with two elements,
eye uses the values of the elements as the number of rows and columns,
respectively. For example:
eye (3)
⇒ 1 0 0
0 1 0
0 0 1
|
The following expressions all produce the same result:
eye (2) ≡ eye (2, 2) ≡ eye (size ([1, 2; 3, 4]) |
The optional argument class, allows eye to return an array of
the specified type, like
val = zeros (n,m, "uint8") |
Calling eye with no arguments is equivalent to calling it
with an argument of 1. Any negative dimensions are treated as zero.
These odd definitions are for compatibility with MATLAB.
Return a matrix or N-dimensional array whose elements are all 1. If invoked with a single scalar integer argument n, return a square NxN matrix. If invoked with two or more scalar integer arguments, or a vector of integer values, return an array with the given dimensions.
If you need to create a matrix whose values are all the same, you should use an expression like
val_matrix = val * ones (m, n) |
The optional argument class specifies the class of the return array and defaults to double. For example:
val = ones (m,n, "uint8") |
See also: zeros.
Return a matrix or N-dimensional array whose elements are all 0. If invoked with a single scalar integer argument, return a square NxN matrix. If invoked with two or more scalar integer arguments, or a vector of integer values, return an array with the given dimensions.
The optional argument class specifies the class of the return array and defaults to double. For example:
val = zeros (m,n, "uint8") |
See also: ones.
Form a block matrix of size m by n, with a copy of matrix A as each element. If n is not specified, form an m by m block matrix. For copying along more than two dimensions, specify the number of times to copy across each dimension m, n, p, …, in a vector in the second argument.
See also: repelems.
Construct a vector of repeated elements from x. r is a 2xN integer matrix specifying which elements to repeat and how often to repeat each element.
Entries in the first row, r(1,j), select an element to repeat. The corresponding entry in the second row, r(2,j), specifies the repeat count. If x is a matrix then the columns of x are imagined to be stacked on top of each other for purposes of the selection index. A row vector is always returned.
Conceptually the result is calculated as follows:
y = []; for i = 1:columns (r) y = [y, x(r(1,i)*ones(1, r(2,i)))]; endfor |
The functions linspace and logspace make it very easy to
create vectors with evenly or logarithmically spaced elements.
See section Ranges.
Return a row vector with n linearly spaced elements between base and limit. If the number of elements is greater than one, then the endpoints base and limit are always included in the range. If base is greater than limit, the elements are stored in decreasing order. If the number of points is not specified, a value of 100 is used.
The linspace function always returns a row vector if both
base and limit are scalars. If one, or both, of them are column
vectors, linspace returns a matrix.
For compatibility with MATLAB, return the second argument (limit) if fewer than two values are requested.
See also: logspace.
Return a row vector with n elements logarithmically spaced from 10^a to 10^b. If n is unspecified it defaults to 50.
If b is equal to pi, the points are between 10^a and pi, not 10^a and 10^pi, in order to be compatible with the corresponding MATLAB function.
Also for compatibility with MATLAB, return the second argument b if fewer than two values are requested.
See also: linspace.
Return a matrix with random elements uniformly distributed on the
interval (0, 1). The arguments are handled the same as the arguments
for eye.
You can query the state of the random number generator using the form
v = rand ("state")
|
This returns a column vector v of length 625. Later, you can restore the random number generator to the state v using the form
rand ("state", v)
|
You may also initialize the state vector from an arbitrary vector of length ≤ 625 for v. This new state will be a hash based on the value of v, not v itself.
By default, the generator is initialized from /dev/urandom if it is
available, otherwise from CPU time, wall clock time, and the current
fraction of a second. Note that this differs from MATLAB, which
always initializes the state to the same state at startup. To obtain
behavior comparable to MATLAB, initialize with a deterministic state
vector in Octave’s startup files (see section Startup Files).
To compute the pseudo-random sequence, rand uses the Mersenne
Twister with a period of 2^19937-1 (See M. Matsumoto and
T. Nishimura,
Mersenne Twister: A 623-dimensionally equidistributed uniform
pseudorandom number generator, ACM Trans. on
Modeling and Computer Simulation Vol. 8, No. 1, pp. 3-30, January 1998,
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html).
Do not use for cryptography without securely hashing
several returned values together, otherwise the generator state
can be learned after reading 624 consecutive values.
Older versions of Octave used a different random number generator.
The new generator is used by default
as it is significantly faster than the old generator, and produces
random numbers with a significantly longer cycle time. However, in
some circumstances it might be desirable to obtain the same random
sequences as used by the old generators. To do this the keyword
"seed" is used to specify that the old generators should be use,
as in
rand ("seed", val)
|
which sets the seed of the generator to val. The seed of the generator can be queried with
s = rand ("seed")
|
However, it should be noted that querying the seed will not cause
rand to use the old generators, only setting the seed will.
To cause rand to once again use the new generators, the
keyword "state" should be used to reset the state of the
rand.
The state or seed of the generator can be reset to a new random value
using the "reset" keyword.
The class of the value returned can be controlled by a trailing
"double" or "single" argument. These are the only valid
classes.
Return random integers in the range 1:imax.
Additional arguments determine the shape of the return matrix. When no arguments are specified a single random integer is returned. If one argument n is specified then a square matrix (n x n) is returned. Two or more arguments will return a multi-dimensional matrix (m x n x …).
The integer range may optionally be described by a two element matrix with a lower and upper bound in which case the returned integers will be on the interval [imin, imax].
The optional argument class will return a matrix of the requested
type. The default is "double".
The following example returns 150 integers in the range 1-10.
ri = randi (10, 150, 1) |
Implementation Note: randi relies internally on rand which
uses class "double" to represent numbers. This limits the maximum
integer (imax) and range (imax - imin) to the value
returned by the bitmax function. For IEEE floating point numbers
this value is 2^53 - 1.
See also: rand.
Return a matrix with normally distributed random
elements having zero mean and variance one. The arguments are
handled the same as the arguments for rand.
By default, randn uses the Marsaglia and Tsang “Ziggurat technique”
to transform from a uniform to a normal distribution.
The class of the value returned can be controlled by a trailing
"double" or "single" argument. These are the only valid
classes.
Reference: G. Marsaglia and W.W. Tsang, Ziggurat Method for Generating Random Variables, J. Statistical Software, vol 5, 2000, http://www.jstatsoft.org/v05/i08/)
Return a matrix with exponentially distributed random elements. The
arguments are handled the same as the arguments for rand.
By default, randn uses the Marsaglia and Tsang “Ziggurat technique”
to transform from a uniform to an exponential distribution.
The class of the value returned can be controlled by a trailing
"double" or "single" argument. These are the only valid
classes.
Reference: G. Marsaglia and W.W. Tsang, Ziggurat Method for Generating Random Variables, J. Statistical Software, vol 5, 2000, http://www.jstatsoft.org/v05/i08/)
Return a matrix with Poisson distributed random elements with mean value
parameter given by the first argument, l. The arguments
are handled the same as the arguments for rand, except for the
argument l.
Five different algorithms are used depending on the range of l and whether or not l is a scalar or a matrix.
W.H. Press, et al., Numerical Recipes in C, Cambridge University Press, 1992.
W.H. Press, et al., Numerical Recipes in C, Cambridge University Press, 1992.
E. Stadlober, et al., WinRand source code, available via FTP.
E. Stadlober, et al., WinRand source code, available via FTP, or H. Zechner, Efficient sampling from continuous and discrete unimodal distributions, Doctoral Dissertation, 156pp., Technical University Graz, Austria, 1994.
L. Montanet, et al., Review of Particle Properties, Physical Review D 50 p1284, 1994.
The class of the value returned can be controlled by a trailing
"double" or "single" argument. These are the only valid
classes.
Return a matrix with gamma (a,1) distributed random elements.
The arguments are handled the same as the arguments for rand,
except for the argument a.
This can be used to generate many distributions:
gamma (a, b) for a > -1, b > 0r = b * randg (a) |
beta (a, b) for a > -1, b > -1r1 = randg (a, 1) r = r1 / (r1 + randg (b, 1)) |
Erlang (a, n)r = a * randg (n) |
chisq (df) for df > 0r = 2 * randg (df / 2) |
t (df) for 0 < df < inf (use randn if df is infinite)r = randn () / sqrt (2 * randg (df / 2) / df) |
F (n1, n2) for 0 < n1, 0 < n2## r1 equals 1 if n1 is infinite r1 = 2 * randg (n1 / 2) / n1 ## r2 equals 1 if n2 is infinite r2 = 2 * randg (n2 / 2) / n2 r = r1 / r2 |
binomial (n, p) for n > 0, 0 < p <= 1r = randp ((1 - p) / p * randg (n)) |
chisq (df, L), for df >= 0 and L > 0(use chisq if L = 0)
r = randp (L / 2) r(r > 0) = 2 * randg (r(r > 0)) r(df > 0) += 2 * randg (df(df > 0)/2) |
Dirichlet (a1, … ak)r = (randg (a1), …, randg (ak)) r = r / sum (r) |
The class of the value returned can be controlled by a trailing
"double" or "single" argument. These are the only valid
classes.
The generators operate in the new or old style together, it is not
possible to mix the two. Initializing any generator with
"state" or "seed" causes the others to switch to the
same style for future calls.
The state of each generator is independent and calls to different generators can be interleaved without affecting the final result. For example,
rand ("state", [11, 22, 33]);
randn ("state", [44, 55, 66]);
u = rand (100, 1);
n = randn (100, 1);
|
and
rand ("state", [11, 22, 33]);
randn ("state", [44, 55, 66]);
u = zeros (100, 1);
n = zeros (100, 1);
for i = 1:100
u(i) = rand ();
n(i) = randn ();
end
|
produce equivalent results. When the generators are initialized in
the old style with "seed" only rand and randn are
independent, because the old rande, randg and
randp generators make calls to rand and randn.
The generators are initialized with random states at start-up, so that the sequences of random numbers are not the same each time you run Octave.(7) If you really do need to reproduce a sequence of numbers exactly, you can set the state or seed to a specific value.
If invoked without arguments, rand and randn return a
single element of a random sequence.
The original rand and randn functions use Fortran code from
RANLIB, a library of Fortran routines for random number generation,
compiled by Barry W. Brown and James Lovato of the Department of
Biomathematics at The University of Texas, M.D. Anderson Cancer Center,
Houston, TX 77030.
Return a row vector containing a random permutation of 1:n.
If m is supplied, return m unique entries, sampled without
replacement from 1:n. The complexity is O(n) in
memory and O(m) in time, unless m < n/5, in which case
O(m) memory is used as well. The randomization is performed using
rand(). All permutations are equally likely.
See also: perms.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following functions return famous matrix forms.
Create interesting matrices for testing.
Create a Cauchy matrix.
Create a Chebyshev spectral differentiation matrix.
Create a Vandermonde-like matrix for the Chebyshev polynomials.
Create a Chow matrix – a singular Toeplitz lower Hessenberg matrix.
Create a circulant matrix.
Create a tridiagonal matrix with zero diagonal entries.
Create a comparison matrix.
Create a ‘counterexample’ matrix to a condition estimator.
Create a matrix whose columns repeat cyclically.
Create a diagonally dominant, ill conditioned, tridiagonal matrix.
Create a (0, 1) matrix whose inverse has large integer entries.
Create a symmetric Fiedler matrix.
Create a Forsythe matrix (a perturbed Jordan block).
Create a Frank matrix (ill conditioned eigenvalues).
Create a greatest common divisor matrix.
c is an n-by-n matrix whose values correspond to the
greatest common divisor of its coordinate values, i.e., c(i,j)
correspond gcd (i, j).
Create a Gear matrix.
Create a Toeplitz matrix with sensitive eigenvalues.
Create a matrix whose eigenvalues lie on a vertical line in the complex plane.
Create a householder matrix.
Create a matrix with random integers in the range [1, imax]. If imin is given then the integers are in the range [imin, imax].
The second input is a matrix of dimensions describing the size of the output. The dimensions can also be input as comma-separated arguments.
The input j is an integer index in the range [0, 2^32-1]. The values of the output matrix are always exactly the same (reproducibility) for a given size input and j index.
The final optional argument determines the class of the resulting matrix.
Possible values for class: "uint8", "uint16",
"uint32", "int8", "int16", int32", "single",
"double". The default is "double".
Create the inverse of an upper Hessenberg matrix.
Create an involutory matrix.
Create an Hankel matrix with factorial elements.
Create a Jordan block.
Create a Kahan matrix (upper trapezoidal).
Create a Kac-Murdock-Szego Toeplitz matrix.
Create a Krylov matrix.
Create a Lauchli matrix (rectangular).
Create a Lehmer matrix (symmetric positive definite).
Create a tridiagonal matrix with real, sensitive eigenvalues.
Create a Lotkin matrix.
Create a symmetric positive definite matrix MIN(i,j).
Create a Moler matrix (symmetric positive definite).
Create a singular matrix from the discrete Neumann problem (sparse).
Create a matrix with random samples from the standard normal distribution (mean = 0, std = 1).
The first input is a matrix of dimensions describing the size of the output. The dimensions can also be input as comma-separated arguments.
The input j is an integer index in the range [0, 2^32-1]. The values of the output matrix are always exactly the same (reproducibility) for a given size input and j index.
The final optional argument determines the class of the resulting matrix.
Possible values for class: "single", "double".
The default is "double".
Create orthogonal and nearly orthogonal matrices.
Create a Parter matrix (a Toeplitz matrix with singular values near pi).
Create a Pei matrix.
Create a block tridiagonal matrix from Poisson’s equation (sparse).
Create a prolate matrix (symmetric, ill-conditioned Toeplitz matrix).
Create a random, orthogonal upper Hessenberg matrix.
Create a random matrix with elements -1, 0 or 1.
Create a random matrix with pre-assigned singular values.
Create a zero and ones matrix of Redheffer associated with the Riemann hypothesis.
Create a matrix associated with the Riemann hypothesis.
Create a symmetric Hankel matrix.
Create a complex matrix, with a ‘smoke ring’ pseudospectrum.
Create a symmetric positive definite Toeplitz matrix.
Create a pentadiagonal Toeplitz matrix (sparse).
Create a tridiagonal matrix (sparse).
Create an upper triangular matrix discussed by Kahan, Golub and Wilkinson.
Create a matrix with random samples from the standard uniform distribution (range [0,1]).
The first input is a matrix of dimensions describing the size of the output. The dimensions can also be input as comma-separated arguments.
The input j is an integer index in the range [0, 2^32-1]. The values of the output matrix are always exactly the same (reproducibility) for a given size input and j index.
The final optional argument determines the class of the resulting matrix.
Possible values for class: "single", "double".
The default is "double".
Create the Wathen matrix.
Create various specific matrices devised/discussed by Wilkinson.
Construct a Hadamard matrix (Hn) of size n-by-n. The
size n must be of the form 2^k * p in which
p is one of 1, 12, 20 or 28. The returned matrix is normalized,
meaning Hn(:,1) == 1 and Hn(1,:) == 1.
Some of the properties of Hadamard matrices are:
kron (Hm, Hn) is a Hadamard matrix of size m-by-n.
Hn * Hn' = n * eye (n).
det (A) <= abs (det (Hn)) for all A with
abs (A(i, j)) <= 1.
Return the Hankel matrix constructed from the first column c, and (optionally) the last row r. If the last element of c is not the same as the first element of r, the last element of c is used. If the second argument is omitted, it is assumed to be a vector of zeros with the same size as c.
A Hankel matrix formed from an m-vector c, and an n-vector r, has the elements
H(i,j) = c(i+j-1), i+j-1 <= m; H(i,j) = r(i+j-m), otherwise |
Return the Hilbert matrix of order n. The i,j element of a Hilbert matrix is defined as
H(i, j) = 1 / (i + j - 1) |
Hilbert matrices are close to being singular which make them difficult to invert with numerical routines. Comparing the condition number of a random matrix 5x5 matrix with that of a Hilbert matrix of order 5 reveals just how difficult the problem is.
cond (rand (5)) ⇒ 14.392 cond (hilb (5)) ⇒ 4.7661e+05 |
See also: invhilb.
Return the inverse of the Hilbert matrix of order n. This can be computed exactly using
(i+j) /n+i-1\ /n+j-1\ /i+j-2\ 2
A(i,j) = -1 (i+j-1)( )( ) ( )
\ n-j / \ n-i / \ i-2 /
= p(i) p(j) / (i+j-1)
|
where
k /k+n-1\ /n\
p(k) = -1 ( ) ( )
\ k-1 / \k/
|
The validity of this formula can easily be checked by expanding the binomial coefficients in both formulas as factorials. It can be derived more directly via the theory of Cauchy matrices. See J. W. Demmel, Applied Numerical Linear Algebra, p. 92.
Compare this with the numerical calculation of inverse (hilb (n)),
which suffers from the ill-conditioning of the Hilbert matrix, and the
finite precision of your computer’s floating point arithmetic.
See also: hilb.
Create an n-by-n magic square. A magic square is an arrangement
of the integers 1:n^2 such that the row sums, column sums, and
diagonal sums are all equal to the same value.
Note: n must be greater than 2 for the magic square to exist.
Return the Pascal matrix of order n if t = 0. t
defaults to 0. Return the pseudo-lower triangular Cholesky factor of
the Pascal matrix if t = 1 (The sign of some columns may be
negative). This matrix is its own inverse, that is pascal (n,
1) ^ 2 == eye (n). If t = -1, return the true
Cholesky factor with strictly positive values on the diagonal. If
t = 2, return a transposed and permuted version of pascal
(n, 1), which is the cube root of the identity matrix. That is,
pascal (n, 2) ^ 3 == eye (n).
See also: chol.
Return the Rosser matrix. This is a difficult test case used to evaluate eigenvalue algorithms.
Return the Toeplitz matrix constructed from the first column c, and (optionally) the first row r. If the first element of r is not the same as the first element of c, the first element of c is used. If the second argument is omitted, the first row is taken to be the same as the first column.
A square Toeplitz matrix has the form:
c(0) r(1) r(2) … r(n) c(1) c(0) r(1) … r(n-1) c(2) c(1) c(0) … r(n-2) . . . . . . . . . . . . . . . c(n) c(n-1) c(n-2) … c(0) |
See also: hankel.
Return the Vandermonde matrix whose next to last column is c. If n is specified, it determines the number of columns; otherwise, n is taken to be equal to the length of c.
A Vandermonde matrix has the form:
c(1)^(n-1) … c(1)^2 c(1) 1
c(2)^(n-1) … c(2)^2 c(2) 1
. . . . .
. . . . .
. . . . .
c(n)^(n-1) … c(n)^2 c(n) 1
|
See also: polyfit.
Return the Wilkinson matrix of order n. Wilkinson matrices are symmetric and tridiagonal with pairs of nearly, but not exactly, equal eigenvalues. They are useful in testing the behavior and performance of eigenvalue solvers.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Unless otherwise noted, all of the functions described in this chapter will work for real and complex scalar, vector, or matrix arguments. Functions described as mapping functions apply the given operation individually to each element when given a matrix argument. For example:
sin ([1, 2; 3, 4])
⇒ 0.84147 0.90930
0.14112 -0.75680
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Compute
e^x
for each element of x. To compute the matrix
exponential, see Linear Algebra.
See also: log.
Compute
exp (x) - 1
accurately in the neighborhood of zero.
See also: exp.
Compute the natural logarithm,
ln (x),
for each element of x. To compute the
matrix logarithm, see Linear Algebra.
Return the real-valued natural logarithm of each element of x. Report an error if any element results in a complex return value.
Compute
log (1 + x)
accurately in the neighborhood of zero.
Compute the base-10 logarithm of each element of x.
Compute the base-2 logarithm of each element of x.
If called with two output arguments, split x into
binary mantissa and exponent so that
1/2 <= abs(f) < 1
and e is an integer. If
x = 0, f = e = 0.
With one argument, computes 2 .^ x for each element of x.
With two arguments, returns f .* (2 .^ e).
If x is a scalar, return the first integer n such that 2^n ≥ abs (x).
If x is a vector, return nextpow2 (length (x)).
Compute the real-valued, element-by-element power operator. This is
equivalent to x .^ y, except that realpow
reports an error if any return value is complex.
Compute the square root of each element of x. If x is negative, a complex result is returned. To compute the matrix square root, see Linear Algebra.
Return the real-valued square root of each element of x. Report an error if any element results in a complex return value.
Compute the real cube root of each element of x.
Unlike x^(1/3), the result will be negative if x is
negative.
See also: nthroot.
Compute the n-th root of x, returning real results for real components of x. For example:
nthroot (-1, 3) ⇒ -1 (-1) ^ (1 / 3) ⇒ 0.50000 - 0.86603i |
x must have all real entries. n must be a scalar. If n is an even integer and X has negative entries, an error is produced.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In the descriptions of the following functions,
z is the complex number x + iy, where i is
defined as sqrt (-1).
Compute the magnitude of z, defined as
|z| = sqrt (x^2 + y^2).
For example:
abs (3 + 4i)
⇒ 5
|
Compute the argument of z, defined as,
theta = atan2 (y, x),
in radians.
For example:
arg (3 + 4i)
⇒ 0.92730
|
Return the complex conjugate of z, defined as
conj (z) = x - iy.
Sort the numbers z into complex conjugate pairs ordered by
increasing real part. Place the negative imaginary complex number
first within each pair. Place all the real numbers (those with
abs (imag (z) / z) < tol)) after the
complex pairs.
If tol is unspecified the default value is 100*eps.
By default the complex pairs are sorted along the first non-singleton dimension of z. If dim is specified, then the complex pairs are sorted along this dimension.
Signal an error if some complex numbers could not be paired. Signal an error if all complex numbers are not exact conjugates (to within tol). Note that there is no defined order for pairs with identical real parts but differing imaginary parts.
cplxpair (exp(2i*pi*[0:4]'/5)) == exp(2i*pi*[3; 2; 4; 1; 0]/5) |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave provides the following trigonometric functions where angles are
specified in radians. To convert from degrees to radians multiply by
pi/180
(e.g., sin (30 * pi/180) returns the sine of 30 degrees). As
an alternative, Octave provides a number of trigonometric functions
which work directly on an argument specified in degrees. These functions
are named after the base trigonometric function with a ‘d’ suffix. For
example, sin expects an angle in radians while sind expects an
angle in degrees.
Octave uses the C library trigonometric functions. It is expected that these
functions are defined by the ISO/IEC 9899 Standard. This Standard is available
at: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf.
Section F.9.1 deals with the trigonometric functions. The behavior of most of
the functions is relatively straightforward. However, there are some
exceptions to the standard behavior. Many of the exceptions involve the
behavior for -0. The most complex case is atan2. Octave exactly implements
the behavior given in the Standard. Including
atan2(+- 0, 0) returns +- pi.
It should be noted that MATLAB uses different definitions which apparently do not distinguish -0.
Compute the sine for each element of x in radians.
Compute the cosine for each element of x in radians.
Compute the tangent for each element of x in radians.
Compute the secant for each element of x in radians.
Compute the cosecant for each element of x in radians.
Compute the cotangent for each element of x in radians.
Compute the inverse sine in radians for each element of x.
Compute the inverse cosine in radians for each element of x.
Compute the inverse tangent in radians for each element of x.
Compute the inverse secant in radians for each element of x.
Compute the inverse cosecant in radians for each element of x.
Compute the inverse cotangent in radians for each element of x.
Compute the hyperbolic sine for each element of x.
Compute the hyperbolic cosine for each element of x.
Compute hyperbolic tangent for each element of x.
Compute the hyperbolic secant of each element of x.
See also: asech.
Compute the hyperbolic cosecant of each element of x.
See also: acsch.
Compute the hyperbolic cotangent of each element of x.
See also: acoth.
Compute the inverse hyperbolic sine for each element of x.
See also: sinh.
Compute the inverse hyperbolic cosine for each element of x.
See also: cosh.
Compute the inverse hyperbolic tangent for each element of x.
See also: tanh.
Compute the inverse hyperbolic secant of each element of x.
See also: sech.
Compute the inverse hyperbolic cosecant of each element of x.
See also: csch.
Compute the inverse hyperbolic cotangent of each element of x.
See also: coth.
Compute atan (y / x) for corresponding elements of y and x. Signal an error if y and x do not match in size and orientation.
Octave provides the following trigonometric functions where angles are specified in degrees. These functions produce true zeros at the appropriate intervals rather than the small round-off error that occurs when using radians. For example:
cosd (90)
⇒ 0
cos (pi/2)
⇒ 6.1230e-17
|
Compute the sine for each element of x in degrees. Returns zero
for elements where x/180 is an integer.
Compute the cosine for each element of x in degrees. Returns zero
for elements where (x-90)/180 is an integer.
Compute the tangent for each element of x in degrees. Returns zero
for elements where x/180 is an integer and Inf for
elements where (x-90)/180 is an integer.
Compute the cosecant for each element of x in degrees.
Compute the cotangent for each element of x in degrees.
Compute the inverse sine in degrees for each element of x.
Compute the inverse cosine in degrees for each element of x.
Compute the inverse tangent in degrees for each element of x.
Compute atan2 (y / x) in degrees for corresponding elements from y and x.
Compute the inverse secant in degrees for each element of x.
Compute the inverse cosecant in degrees for each element of x.
Compute the inverse cotangent in degrees for each element of x.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Sum of elements along dimension dim. If dim is omitted, it defaults to the first non-singleton dimension.
If the optional argument "native" is given, then the sum is
performed in the same type as the original argument, rather than in the
default double type. For example:
sum ([true, true]) ⇒ 2 sum ([true, true], "native") ⇒ true |
On the contrary, if "double" is given, the sum is performed in
double precision even for single precision inputs.
For double precision inputs, "extra" indicates that a more accurate
algorithm than straightforward summation is to be used. For single precision
inputs, "extra" is the same as "double". Otherwise,
"extra" has no effect.
Product of elements along dimension dim. If dim is omitted, it defaults to the first non-singleton dimension.
Cumulative sum of elements along dimension dim. If dim is omitted, it defaults to the first non-singleton dimension.
See sum for an explanation of the optional parameters
"native", "double", and "extra".
Cumulative product of elements along dimension dim. If dim is omitted, it defaults to the first non-singleton dimension.
Sum of squares of elements along dimension dim. If dim is omitted, it defaults to the first non-singleton dimension.
This function is conceptually equivalent to computing
sum (x .* conj (x), dim) |
but it uses less memory and avoids calling conj if x is real.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Return the smallest integer not less than x. This is equivalent to
rounding towards positive infinity. If x is
complex, return ceil (real (x)) + ceil (imag (x)) * I.
ceil ([-2.7, 2.7])
⇒ -2 3
|
Truncate fractional portion of x and return the integer portion. This
is equivalent to rounding towards zero. If x is complex, return
fix (real (x)) + fix (imag (x)) * I.
fix ([-2.7, 2.7]) ⇒ -2 2 |
Return the largest integer not greater than x. This is equivalent to
rounding towards negative infinity. If x is
complex, return floor (real (x)) + floor (imag (x)) * I.
floor ([-2.7, 2.7])
⇒ -3 2
|
Return the integer nearest to x. If x is complex, return
round (real (x)) + round (imag (x)) * I. If there
are two nearest integers, return the one further away from zero.
round ([-2.7, 2.7])
⇒ -3 3
|
Return the integer nearest to x. If there are two nearest
integers, return the even one (banker’s rounding). If x is complex,
return roundb (real (x)) + roundb (imag (x)) * I.
See also: round.
For a vector argument, return the maximum value. For a matrix argument, return the maximum value from each column, as a row vector, or over the dimension dim if defined, in which case y should be set to the empty matrix (it’s ignored otherwise). For two matrices (or a matrix and scalar), return the pair-wise maximum. Thus,
max (max (x)) |
returns the largest element of the matrix x, and
max (2:5, pi)
⇒ 3.1416 3.1416 4.0000 5.0000
|
compares each element of the range 2:5 with pi, and
returns a row vector of the maximum values.
For complex arguments, the magnitude of the elements are used for comparison.
If called with one input and two output arguments,
max also returns the first index of the
maximum value(s). Thus,
[x, ix] = max ([1, 3, 5, 2, 5])
⇒ x = 5
ix = 3
|
For a vector argument, return the minimum value. For a matrix argument, return the minimum value from each column, as a row vector, or over the dimension dim if defined, in which case y should be set to the empty matrix (it’s ignored otherwise). For two matrices (or a matrix and scalar), return the pair-wise minimum. Thus,
min (min (x)) |
returns the smallest element of x, and
min (2:5, pi)
⇒ 2.0000 3.0000 3.1416 3.1416
|
compares each element of the range 2:5 with pi, and
returns a row vector of the minimum values.
For complex arguments, the magnitude of the elements are used for comparison.
If called with one input and two output arguments,
min also returns the first index of the
minimum value(s). Thus,
[x, ix] = min ([1, 3, 0, 2, 0])
⇒ x = 0
ix = 3
|
Return the cumulative maximum values along dimension dim.
If dim is unspecified it defaults to column-wise operation. For example:
cummax ([1 3 2 6 4 5]) ⇒ 1 3 3 6 6 6 |
If called with two output arguments the index of the maximum value is also returned.
[w, iw] = cummax ([1 3 2 6 4 5]) ⇒ w = 1 3 3 6 6 6 iw = 1 2 2 4 4 4 |
Return the cumulative minimum values along dimension dim.
If dim is unspecified it defaults to column-wise operation. For example:
cummin ([5 4 6 2 3 1]) ⇒ 5 4 4 2 2 1 |
If called with two output arguments the index of the minimum value is also returned.
[w, iw] = cummin ([5 4 6 2 3 1]) ⇒ w = 5 4 4 2 2 1 iw = 1 2 2 4 4 6 |
Compute the element-by-element square root of the sum of the squares of
x and y. This is equivalent to
sqrt (x.^2 + y.^2), but calculated in a manner that
avoids overflows for large values of x or y.
hypot can also be called with more than 2 arguments; in this case,
the arguments are accumulated from left to right:
hypot (hypot (x, y), z) hypot (hypot (hypot (x, y), z), w), etc. |
Calculate the gradient of sampled data or a function. If m is a vector, calculate the one-dimensional gradient of m. If m is a matrix the gradient is calculated for each dimension.
[dx, dy] = gradient (m) calculates the one
dimensional gradient for x and y direction if m is a
matrix. Additional return arguments can be use for multi-dimensional
matrices.
A constant spacing between two points can be provided by the s parameter. If s is a scalar, it is assumed to be the spacing for all dimensions. Otherwise, separate values of the spacing can be supplied by the x, … arguments. Scalar values specify an equidistant spacing. Vector values for the x, … arguments specify the coordinate for that dimension. The length must match their respective dimension of m.
At boundary points a linear extrapolation is applied. Interior points are calculated with the first approximation of the numerical gradient
y'(i) = 1/(x(i+1)-x(i-1)) * (y(i-1)-y(i+1)). |
If the first argument f is a function handle, the gradient of the
function at the points in x0 is approximated using central
difference. For example, gradient (@cos, 0) approximates the
gradient of the cosine function in the point x0 = 0. As with
sampled data, the spacing values between the points from which the
gradient is estimated can be set via the s or dx,
dy, … arguments. By default a spacing of 1 is used.
Compute the dot product of two vectors. If x and y are matrices, calculate the dot products along the first non-singleton dimension. If the optional argument dim is given, calculate the dot products along this dimension.
This is equivalent to
sum (conj (X) .* Y, dim),
but avoids forming a temporary array and is faster. When X and
Y are column vectors, the result is equivalent to
X' * Y.
See also: cross, divergence.
Compute the vector cross product of two 3-dimensional vectors x and y.
cross ([1,1,0], [0,1,1])
⇒ [ 1; -1; 1 ]
|
If x and y are matrices, the cross product is applied along the first dimension with 3 elements. The optional argument dim forces the cross product to be calculated along the specified dimension.
See also: dot, curl, divergence.
Calculate divergence of a vector field given by the arrays fx, fy, and fz or fx, fy respectively.
d d d
div F(x,y,z) = -- F(x,y,z) + -- F(x,y,z) + -- F(x,y,z)
dx dy dz
|
The coordinates of the vector field can be given by the arguments x, y, z or x, y respectively.
Calculate curl of vector field given by the arrays fx, fy, and fz or fx, fy respectively.
/ d d d d d d \
curl F(x,y,z) = | -- Fz - -- Fy, -- Fx - -- Fz, -- Fy - -- Fx |
\ dy dz dz dx dx dy /
|
The coordinates of the vector field can be given by the arguments x, y, z or x, y respectively. v calculates the scalar component of the angular velocity vector in direction of the z-axis for two-dimensional input. For three-dimensional input the scalar rotation is calculated at each grid point in direction of the vector field at that point.
See also: divergence, gradient, del2, cross.
Calculate the discrete Laplace operator. For a 2-dimensional matrix M this is defined as
1 / d^2 d^2 \
D = --- * | --- M(x,y) + --- M(x,y) |
4 \ dx^2 dy^2 /
|
For N-dimensional arrays the sum in parentheses is expanded to include second derivatives over the additional higher dimensions.
The spacing between evaluation points may be defined by h, which is a scalar defining the equidistant spacing in all dimensions. Alternatively, the spacing in each dimension may be defined separately by dx, dy, etc. A scalar spacing argument defines equidistant spacing, whereas a vector argument can be used to specify variable spacing. The length of the spacing vectors must match the respective dimension of M. The default spacing value is 1.
At least 3 data points are needed for each dimension. Boundary points are calculated from the linear extrapolation of interior points.
Return the factorial of n where n is a positive integer. If
n is a scalar, this is equivalent to prod (1:n). For
vector or matrix arguments, return the factorial of each element in the
array. For non-integers see the generalized factorial function
gamma.
Return the prime factorization of q. That is,
prod (p) == q and every element of p is a prime
number. If q == 1, return 1.
With two output arguments, return the unique primes p and
their multiplicities. That is, prod (p .^ n) ==
q.
Implementation Note: The input q must not be greater than
bitmax (9.0072e+15) in order to factor correctly.
Compute the greatest common divisor of a1, a2, …. If more than one argument is given all arguments must be the same size or scalar. In this case the greatest common divisor is calculated for each element individually. All elements must be ordinary or Gaussian (complex) integers. Note that for Gaussian integers, the gcd is not unique up to units (multiplication by 1, -1, i or -i), so an arbitrary greatest common divisor amongst four possible is returned.
Example code:
gcd ([15, 9], [20, 18]) ⇒ 5 9 |
Optional return arguments v1, etc., contain integer vectors such that,
g = v1 .* a1 + v2 .* a2 + … |
Compute the least common multiple of x and y, or of the list of all arguments. All elements must be the same size or scalar.
Truncate elements of x to a length of ndigits such that the resulting numbers are exactly divisible by base. If base is not specified it defaults to 10.
chop (-pi, 5, 10) ⇒ -3.14200000000000 chop (-pi, 5, 5) ⇒ -3.14150000000000 |
Return the remainder of the division x / y, computed
using the expression
x - y .* fix (x ./ y) |
An error message is printed if the dimensions of the arguments do not agree, or if either of the arguments is complex.
See also: mod.
Compute the modulo of x and y. Conceptually this is given by
x - y .* floor (x ./ y) |
and is written such that the correct modulus is returned for
integer types. This function handles negative values correctly. That
is, mod (-1, 3) is 2, not -1, as rem (-1, 3) returns.
mod (x, 0) returns x.
An error results if the dimensions of the arguments do not agree, or if either of the arguments is complex.
See also: rem.
Return all primes up to n.
The algorithm used is the Sieve of Eratosthenes.
Note that if you need a specific number of primes you can use the fact that the distance from one prime to the next is, on average, proportional to the logarithm of the prime. Integrating, one finds that there are about k primes less than k*log (5*k).
See also: list_primes, isprime.
List the first n primes. If n is unspecified, the first 25 primes are listed.
The algorithm used is from page 218 of the TeXbook.
Compute the signum function, which is defined as
-1, x < 0;
sign (x) = 0, x = 0;
1, x > 0.
|
For complex arguments, sign returns x ./ abs (x).
Note that sign (-0.0) is 0.
Although IEEE 754 floating point
allows zero to be signed, 0.0 and -0.0 compare equal. If you must test
whether zero is signed, use the signbit function.
See also: signbit.
Return logical true if the value of x has its sign bit set. Otherwise return logical false. This behavior is consistent with the other logical functions. SeeLogical Values. The behavior differs from the C language function which returns non-zero if the sign bit is set.
This is not the same as x < 0.0, because IEEE 754 floating point
allows zero to be signed. The comparison -0.0 < 0.0 is false,
but signbit (-0.0) will return a nonzero value.
See also: sign.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Compute Airy functions of the first and second kind, and their derivatives.
K Function Scale factor (if "opt" is supplied) --- -------- --------------------------------------- 0 Ai (Z) exp ((2/3) * Z * sqrt (Z)) 1 dAi(Z)/dZ exp ((2/3) * Z * sqrt (Z)) 2 Bi (Z) exp (-abs (real ((2/3) * Z * sqrt (Z)))) 3 dBi(Z)/dZ exp (-abs (real ((2/3) * Z * sqrt (Z)))) |
The function call airy (z) is equivalent to
airy (0, z).
The result is the same size as z.
If requested, ierr contains the following status information and is the same size as the result.
NaN.
Inf.
NaN.
NaN.
Compute Bessel or Hankel functions of various kinds:
besseljBessel functions of the first kind. If the argument opt is supplied,
the result is multiplied by exp (-abs (imag (x))).
besselyBessel functions of the second kind. If the argument opt is supplied,
the result is multiplied by exp (-abs (imag (x))).
besseliModified Bessel functions of the first kind. If the argument opt is
supplied, the result is multiplied by exp (-abs (real (x))).
besselkModified Bessel functions of the second kind. If the argument opt is
supplied, the result is multiplied by exp (x).
besselhCompute Hankel functions of the first (k = 1) or second (k
= 2) kind. If the argument opt is supplied, the result is multiplied
by exp (-I*x) for k = 1 or exp (I*x) for
k = 2.
If alpha is a scalar, the result is the same size as x.
If x is a scalar, the result is the same size as alpha.
If alpha is a row vector and x is a column vector, the
result is a matrix with length (x) rows and
length (alpha) columns. Otherwise, alpha and
x must conform and the result will be the same size.
The value of alpha must be real. The value of x may be complex.
If requested, ierr contains the following status information and is the same size as the result.
NaN.
Inf.
NaN.
NaN.
For real inputs, return the Beta function,
beta (a, b) = gamma (a) * gamma (b) / gamma (a + b). |
Return the regularized incomplete Beta function,
x
1 /
betainc (x, a, b) = ----------- | t^(a-1) (1-t)^(b-1) dt.
beta (a, b) /
t=0
|
If x has more than one component, both a and b must be scalars. If x is a scalar, a and b must be of compatible dimensions.
See also: betaincinv, beta, betaln.
Compute the inverse of the incomplete Beta function, i.e., x such that
y == betainc (x, a, b) |
Return the natural logarithm of the Beta function,
betaln (a, b) = log (beta (a, b)) |
calculated in a way to reduce the occurrence of underflow.
Return the binomial coefficient of n and k, defined as
/ \ | n | n (n-1) (n-2) … (n-k+1) | | = ------------------------- | k | k! \ / |
For example:
bincoeff (5, 2) ⇒ 10 |
In most cases, the nchoosek function is faster for small
scalar integer arguments. It also warns about loss of precision for
big arguments.
See also: nchoosek.
Return the commutation matrix K(m,n) which is the unique m*n by m*n matrix such that K(m,n) * vec(A) = vec(A’) for all m by n matrices A.
If only one argument m is given, K(m,m) is returned.
See Magnus and Neudecker (1988), Matrix Differential Calculus with Applications in Statistics and Econometrics.
Return the duplication matrix Dn which is the unique n^2 by n*(n+1)/2 matrix such that Dn vech (A) = vec (A) for all symmetric n by n matrices A.
See Magnus and Neudecker (1988), Matrix differential calculus with applications in statistics and econometrics.
Compute the Dawson (scaled imaginary error) function,
(sqrt (pi) / 2) * exp (-z^2) * erfi (z) |
Compute the Jacobi elliptic functions sn, cn, and dn of complex argument u and real parameter m.
If m is a scalar, the results are the same size as u.
If u is a scalar, the results are the same size as m.
If u is a column vector and m is a row vector, the
results are matrices with length (u) rows and
length (m) columns. Otherwise, u and
m must conform in size and the results will be the same size as the
inputs.
The value of u may be complex. The value of m must be 0 ≤ m ≤ 1.
The optional input tol is currently ignored (MATLAB uses this to allow faster, less accurate approximation).
If requested, err contains the following status information and is the same size as the result.
NaN.
Reference: Milton Abramowitz and Irene A Stegun, Handbook of Mathematical Functions, Chapter 16 (Sections 16.4, 16.13, and 16.15), Dover, 1965.
See also: ellipke.
Compute complete elliptic integrals of the first K(m) and second E(m) kind.
m must be a scalar or real array with -Inf ≤ m ≤ 1.
The optional input tol is currently ignored (MATLAB uses this to allow a faster, less accurate approximation).
Called with only one output, elliptic integrals of the first kind are returned.
Reference: Milton Abramowitz and Irene A. Stegun, Handbook of Mathematical Functions, Chapter 17, Dover, 1965.
See also: ellipj.
Compute the error function,
z
2 /
erf (z) = --------- * | e^(-t^2) dt
sqrt (pi) /
t=0
|
Compute the complementary error function,
1 - erf (z).
Compute the scaled complementary error function,
exp (z^2) * erfc (z) |
Compute the imaginary error function,
-i * erf (i*z) |
Compute the inverse error function, i.e., y such that
erf (y) == x |
Compute the inverse complementary error function, i.e., y such that
erfc (y) == x |
Compute the exponential integral:
infinity
/
E_1 (x) = | exp (-t)/t dt
/
x
|
Note: For compatibility, this functions uses the MATLAB definition of the exponential integral. Most other sources refer to this particular value as E_1 (x), and the exponential integral is
infinity
/
Ei (x) = - | exp (-t)/t dt
/
-x
|
The two definitions are related, for positive real values of x, by
E_1 (-x) = -Ei (x) - i*pi.
Compute the Gamma function,
infinity
/
gamma (z) = | t^(z-1) exp (-t) dt.
/
t=0
|
Compute the normalized incomplete gamma function,
x
1 /
gammainc (x, a) = --------- | exp (-t) t^(a-1) dt
gamma (a) /
t=0
|
with the limiting value of 1 as x approaches infinity. The standard notation is P(a,x), e.g., Abramowitz and Stegun (6.5.1).
If a is scalar, then gammainc (x, a) is returned
for each element of x and vice versa.
If neither x nor a is scalar, the sizes of x and
a must agree, and gammainc is applied element-by-element.
By default the incomplete gamma function integrated from 0 to x is
computed. If "upper" is given then the complementary function
integrated from x to infinity is calculated. It should be noted that
gammainc (x, a) ≡ 1 - gammainc (x, a, "upper") |
Compute the Legendre function of degree n and order
m = 0 … N. The optional argument, normalization,
may be one of "unnorm", "sch", or "norm".
The default is "unnorm". The value of n must be a
non-negative scalar integer.
If the optional argument normalization is missing or is
"unnorm", compute the Legendre function of degree n and
order m and return all values for m = 0 … n.
The return value has one dimension more than x.
The Legendre Function of degree n and order m:
m m 2 m/2 d^m P(x) = (-1) * (1-x ) * ---- P(x) n dx^m n |
with Legendre polynomial of degree n:
1 d^n 2 n P(x) = ------ [----(x - 1) ] n 2^n n! dx^n |
legendre (3, [-1.0, -0.9, -0.8]) returns the matrix:
x | -1.0 | -0.9 | -0.8 ------------------------------------ m=0 | -1.00000 | -0.47250 | -0.08000 m=1 | 0.00000 | -1.99420 | -1.98000 m=2 | 0.00000 | -2.56500 | -4.32000 m=3 | 0.00000 | -1.24229 | -3.24000 |
If the optional argument normalization is "sch",
compute the Schmidt semi-normalized associated Legendre function.
The Schmidt semi-normalized associated Legendre function is related
to the unnormalized Legendre functions by the following:
For Legendre functions of degree n and order 0:
0 0 SP(x) = P(x) n n |
For Legendre functions of degree n and order m:
m m m 2(n-m)! 0.5 SP(x) = P(x) * (-1) * [-------] n n (n+m)! |
If the optional argument normalization is "norm",
compute the fully normalized associated Legendre function.
The fully normalized associated Legendre function is related
to the unnormalized Legendre functions by the following:
For Legendre functions of degree n and order m
m m m (n+0.5)(n-m)! 0.5 NP(x) = P(x) * (-1) * [-------------] n n (n+m)! |
Return the natural logarithm of the gamma function of x.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Find a rational approximation to x within the tolerance defined by tol using a continued fraction expansion. For example:
rat (pi) = 3 + 1/(7 + 1/16) = 355/113
rat (e) = 3 + 1/(-4 + 1/(2 + 1/(5 + 1/(-2 + 1/(-7)))))
= 1457/536
|
Called with two arguments returns the numerator and denominator separately as two matrices.
See also: rats.
Convert x into a rational approximation represented as a string. You can convert the string back into a matrix as follows:
r = rats (hilb (4)); x = str2num (r) |
The optional second argument defines the maximum length of the string representing the elements of x. By default len is 9.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Transform Cartesian to polar or cylindrical coordinates.
theta describes the angle relative to the positive x-axis. r is the distance to the z-axis (0, 0, z). x, y (, and z) must be the same shape, or scalar. If called with a single matrix argument then each row of C represents the Cartesian coordinate (x, y (, z)).
If only a single return argument is requested then return a matrix P where each row represents one polar/(cylindrical) coordinate (theta, phi (, z)).
Transform polar or cylindrical to Cartesian coordinates.
theta, r, (and z) must be the same shape, or scalar. theta describes the angle relative to the positive x-axis. r is the distance to the z-axis (0, 0, z). If called with a single matrix argument then each row of P represents the polar/(cylindrical) coordinate (theta, r (, z)).
If only a single return argument is requested then return a matrix C where each row represents one Cartesian coordinate (x, y (, z)).
Transform Cartesian to spherical coordinates.
theta describes the angle relative to the positive x-axis. phi is the angle relative to the xy-plane. r is the distance to the origin (0, 0, 0). x, y, and z must be the same shape, or scalar. If called with a single matrix argument then each row of C represents the Cartesian coordinate (x, y, z).
If only a single return argument is requested then return a matrix S where each row represents one spherical coordinate (theta, phi, r).
Transform spherical to Cartesian coordinates.
theta describes the angle relative to the positive x-axis. phi is the angle relative to the xy-plane. r is the distance to the origin (0, 0, 0). theta, phi, and r must be the same shape, or scalar. If called with a single matrix argument then each row of S represents the spherical coordinate (theta, phi, r).
If only a single return argument is requested then return a matrix C where each row represents one Cartesian coordinate (x, y, z).
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Return a scalar, matrix, or N-dimensional array whose elements are all equal
to the base of natural logarithms. The constant
‘e’ satisfies the equation log (e) = 1.
When called with no arguments, return a scalar with the value e. When
called with a single argument, return a square matrix with the dimension
specified. When called with more than one scalar argument the first two
arguments are taken as the number of rows and columns and any further
arguments specify additional matrix dimensions.
The optional argument class specifies the return type and may be
either "double" or "single".
Return a scalar, matrix, or N-dimensional array whose elements are all equal
to the ratio of the circumference of a circle to its
diameter.
Internally, pi is computed as ‘4.0 * atan (1.0)’.
When called with no arguments, return a scalar with the value of
pi.
When called with a single argument, return a square matrix with the dimension
specified. When called with more than one scalar argument the first two
arguments are taken as the number of rows and columns and any further
arguments specify additional matrix dimensions.
The optional argument class specifies the return type and may be
either "double" or "single".
Return a scalar, matrix, or N-dimensional array whose elements are all equal
to the pure imaginary unit, defined as
sqrt (-1).
I, and its equivalents i, j, and J, are functions so any of the names may be reused for other purposes (such as i for a counter variable).
When called with no arguments, return a scalar with the value i. When
called with a single argument, return a square matrix with the dimension
specified. When called with more than one scalar argument the first two
arguments are taken as the number of rows and columns and any further
arguments specify additional matrix dimensions.
The optional argument class specifies the return type and may be
either "double" or "single".
Return a scalar, matrix or N-dimensional array whose elements are all equal to the IEEE representation for positive infinity.
Infinity is produced when results are too large to be represented using the the IEEE floating point format for numbers. Two common examples which produce infinity are division by zero and overflow.
[ 1/0 e^800 ] ⇒ Inf Inf |
When called with no arguments, return a scalar with the value ‘Inf’.
When called with a single argument, return a square matrix with the dimension
specified. When called with more than one scalar argument the first two
arguments are taken as the number of rows and columns and any further
arguments specify additional matrix dimensions.
The optional argument class specifies the return type and may be
either "double" or "single".
Return a scalar, matrix, or N-dimensional array whose elements are all equal to the IEEE symbol NaN (Not a Number). NaN is the result of operations which do not produce a well defined numerical result. Common operations which produce a NaN are arithmetic with infinity (Inf - Inf), zero divided by zero (0/0), and any operation involving another NaN value (5 + NaN).
Note that NaN always compares not equal to NaN (NaN != NaN). This behavior
is specified by the IEEE standard for floating point arithmetic. To
find NaN values, use the isnan function.
When called with no arguments, return a scalar with the value ‘NaN’.
When called with a single argument, return a square matrix with the dimension
specified. When called with more than one scalar argument the first two
arguments are taken as the number of rows and columns and any further
arguments specify additional matrix dimensions.
The optional argument class specifies the return type and may be
either "double" or "single".
Return a scalar, matrix or N-dimensional array whose elements are all eps,
the machine precision. More precisely, eps is the relative spacing
between any two adjacent numbers in the machine’s floating point system.
This number is obviously system dependent. On machines that support IEEE
floating point arithmetic, eps is approximately
2.2204e-16 for double precision and 1.1921e-07
for single precision.
When called with no arguments, return a scalar with the value
eps (1.0).
Given a single argument x, return the distance between x and
the next largest value.
When called with more than one argument the first two arguments are taken as
the number of rows and columns and any further
arguments specify additional matrix dimensions.
The optional argument class specifies the return type and may be
either "double" or "single".
Return a scalar, matrix or N-dimensional array whose elements are all equal
to the largest floating point number that is representable. The actual
value is system dependent. On machines that support IEEE
floating point arithmetic, realmax is approximately
1.7977e+308 for double precision and 3.4028e+38
for single precision.
When called with no arguments, return a scalar with the value
realmax (.
When called with a single argument, return a square matrix with the dimension
specified. When called with more than one scalar argument the first two
arguments are taken as the number of rows and columns and any further
arguments specify additional matrix dimensions.
The optional argument class specifies the return type and may be
either "double")"double" or "single".
Return a scalar, matrix or N-dimensional array whose elements are all equal
to the smallest normalized floating point number that is representable.
The actual value is system dependent. On machines that support
IEEE floating point arithmetic, realmin is approximately
2.2251e-308 for double precision and 1.1755e-38
for single precision.
When called with no arguments, return a scalar with the value
realmin (.
When called with a single argument, return a square matrix with the dimension
specified. When called with more than one scalar argument the first two
arguments are taken as the number of rows and columns and any further
arguments specify additional matrix dimensions.
The optional argument class specifies the return type and may be
either "double")"double" or "single".
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This chapter documents the linear algebra functions provided in Octave. Reference material for many of these functions may be found in Golub and Van Loan, Matrix Computations, 2nd Ed., Johns Hopkins, 1989, and in the LAPACK Users’ Guide, SIAM, 1992. The LAPACK Users’ Guide is available at: http://www.netlib.org/lapack/lug/
A common text for engineering courses is G. Strang, Linear Algebra and Its Applications, 4th Edition. It has become a widespread reference for linear algebra. An alternative is P. Lax Linear Algebra and Its Applications, and also is a good choice. It claims to be suitable for high school students with substantial mathematical interests as well as first-year undergraduates.
| 18.1 Techniques Used for Linear Algebra | ||
| 18.2 Basic Matrix Functions | ||
| 18.3 Matrix Factorizations | ||
| 18.4 Functions of a Matrix | ||
| 18.5 Specialized Solvers |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave includes a polymorphic solver that selects an appropriate matrix factorization depending on the properties of the matrix itself. Generally, the cost of determining the matrix type is small relative to the cost of factorizing the matrix itself. In any case the matrix type is cached once it is calculated so that it is not re-determined each time it is used in a linear equation.
The selection tree for how the linear equation is solved or a matrix inverse is formed is given by:
The user can force the type of the matrix with the matrix_type
function. This overcomes the cost of discovering the type of the matrix.
However, it should be noted that identifying the type of the matrix incorrectly
will lead to unpredictable results, and so matrix_type should be
used with care.
It should be noted that the test for whether a matrix is a candidate for
Cholesky factorization, performed above, and by the matrix_type
function, does not make certain that the matrix is
Hermitian. However, the attempt to factorize the matrix will quickly
detect a non-Hermitian matrix.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Compute AA = DD \ A * DD in which AA
is a matrix whose row and column norms are roughly equal in magnitude, and
DD = P * D, in which P is a permutation
matrix and D is a diagonal matrix of powers of two. This allows the
equilibration to be computed without round-off. Results of eigenvalue
calculation are typically improved by balancing first.
If two output values are requested, balance returns
the diagonal D and the permutation P separately as vectors.
In this case, DD = eye(n)(:,P) * diag (D), where
n is the matrix size.
If four output values are requested, compute AA =
CC*A*DD and BB = CC*B*DD,
in which AA and BB have non-zero elements of approximately the
same magnitude and CC and DD are permuted diagonal matrices as
in DD for the algebraic eigenvalue problem.
The eigenvalue balancing option opt may be one of:
"noperm", "S"Scale only; do not permute.
"noscal", "P"Permute only; do not scale.
Algebraic eigenvalue balancing uses standard LAPACK routines.
Generalized eigenvalue problem balancing uses Ward’s algorithm (SIAM Journal on Scientific and Statistical Computing, 1981).
Compute the p-norm condition number of a matrix.
cond (A) is defined as
norm (A, p) * norm (inv (A), p).
By default, p = 2 is used which implies a (relatively slow)
singular value decomposition. Other possible selections are
p = 1, Inf, "fro" which are generally faster. See
norm for a full discussion of possible p values.
The condition number of a matrix quantifies the sensitivity of the matrix inversion operation when small changes are made to matrix elements. Ideally the condition number will be close to 1. When the number is large this indicates small changes (such as underflow or round-off error) will produce large changes in the resulting output. In such cases the solution results from numerical computing are not likely to be accurate.
Compute the determinant of A.
Return an estimate of the reciprocal condition number if requested.
Routines from LAPACK are used for full matrices and code from UMFPACK is used for sparse matrices.
The determinant should not be used to check a matrix for singularity.
For that, use any of the condition number functions: cond,
condest, rcond.
Compute the eigenvalues (and optionally the eigenvectors) of a matrix or a pair of matrices
The algorithm used depends on whether there are one or two input matrices, if they are real or complex and if they are symmetric (Hermitian if complex) or non-symmetric.
The eigenvalues returned by eig are not ordered.
Return a 2 by 2 orthogonal matrix
g = [c s; -s' c] such that
g [x; y] = [*; 0] with x and y scalars.
For example:
givens (1, 1)
⇒ 0.70711 0.70711
-0.70711 0.70711
|
Given a two-element column vector, returns the
2 by 2 orthogonal matrix
G such that
y = g * x and y(2) = 0.
See also: givens.
Compute the inverse of the square matrix A. Return an estimate of the reciprocal condition number if requested, otherwise warn of an ill-conditioned matrix if the reciprocal condition number is small.
In general it is best to avoid calculating the inverse of a matrix
directly. For example, it is both faster and more accurate to solve
systems of equations (A*x = b) with
y = A \ b, rather than
y = inv (A) * b.
If called with a sparse matrix, then in general x will be a full matrix requiring significantly more storage. Avoid forming the inverse of a sparse matrix if possible.
Solve the linear system A*x = b.
With no options, this function is equivalent to the left division operator
(x = A \ b) or the matrix-left-divide function
(x = mldivide (A, b)).
Octave ordinarily examines the properties of the matrix A and chooses
a solver that best matches the matrix. By passing a structure opts
to linsolve you can inform Octave directly about the matrix A.
In this case Octave will skip the matrix examination and proceed directly
to solving the linear system.
Warning: If the matrix A does not have the properties listed in the opts structure then the result will not be accurate AND no warning will be given. When in doubt, let Octave examine the matrix and choose the appropriate solver as this step takes little time and the result is cached so that it is only done once per linear system.
Possible opts fields (set value to true/false):
A is lower triangular
A is upper triangular
A is upper Hessenberg (currently makes no difference)
A is symmetric or complex Hermitian (currently makes no difference)
A is positive definite
A is general rectangular (currently makes no difference)
Solve A'*x = b by transpose (A) \ b
The optional second output R is the inverse condition number of A (zero if matrix is singular).
See also: mldivide, matrix_type, rcond.
Identify the matrix type or mark a matrix as a particular type. This allows
more rapid solutions of linear equations involving A to be performed.
Called with a single argument, matrix_type returns the type of the
matrix and caches it for future use. Called with more than one argument,
matrix_type allows the type of the matrix to be defined.
If the option "nocompute" is given, the function will not attempt
to guess the type if it is still unknown. This is useful for debugging
purposes.
The possible matrix types depend on whether the matrix is full or sparse, and can be one of the following
"unknown"Remove any previously cached matrix type, and mark type as unknown.
"full"Mark the matrix as full.
"positive definite"Probable full positive definite matrix.
"diagonal"Diagonal matrix. (Sparse matrices only)
"permuted diagonal"Permuted Diagonal matrix. The permutation does not need to be specifically indicated, as the structure of the matrix explicitly gives this. (Sparse matrices only)
"upper"Upper triangular. If the optional third argument perm is given, the matrix is assumed to be a permuted upper triangular with the permutations defined by the vector perm.
"lower"Lower triangular. If the optional third argument perm is given, the matrix is assumed to be a permuted lower triangular with the permutations defined by the vector perm.
"banded""banded positive definite"Banded matrix with the band size of nl below the diagonal and nu above it. If nl and nu are 1, then the matrix is tridiagonal and treated with specialized code. In addition the matrix can be marked as probably a positive definite. (Sparse matrices only)
"singular"The matrix is assumed to be singular and will be treated with a minimum norm solution.
Note that the matrix type will be discovered automatically on the first
attempt to solve a linear equation involving A. Therefore
matrix_type is only useful to give Octave hints of the matrix type.
Incorrectly defining the matrix type will result in incorrect results from
solutions of linear equations; it is entirely the responsibility of
the user to correctly identify the matrix type.
Also, the test for positive definiteness is a low-cost test for a Hermitian
matrix with a real positive diagonal. This does not guarantee that the
matrix is positive definite, but only that it is a probable candidate. When
such a matrix is factorized, a Cholesky factorization is first
attempted, and if that fails the matrix is then treated with an
LU factorization. Once the matrix has been factorized,
matrix_type will return the correct classification of the matrix.
Compute the p-norm of the matrix A. If the second argument is
missing, p = 2 is assumed.
If A is a matrix (or sparse matrix):
11-norm, the largest column sum of the absolute values of A.
2Largest singular value of A.
Inf or "inf"Infinity norm, the largest row sum of the absolute values of A.
"fro"Frobenius norm of A, sqrt (sum (diag (A' * A))).
p > 1maximum norm (A*x, p) such that norm (x, p) == 1
If A is a vector or a scalar:
Inf or "inf"max (abs (A)).
-Infmin (abs (A)).
"fro"Frobenius norm of A, sqrt (sumsq (abs (A))).
Hamming norm - the number of nonzero elements.
p > 1p-norm of A, (sum (abs (A) .^ p)) ^ (1/p).
p < 1the p-pseudonorm defined as above.
If opt is the value "rows", treat each row as a vector and
compute its norm. The result is returned as a column vector.
Similarly, if opt is "columns" or "cols" then
compute the norms of each column and return a row vector.
Return an orthonormal basis of the null space of A.
The dimension of the null space is taken as the number of singular values of A not greater than tol. If the argument tol is missing, it is computed as
max (size (A)) * max (svd (A)) * eps |
See also: orth.
Return an orthonormal basis of the range space of A.
The dimension of the range space is taken as the number of singular values of A greater than tol. If the argument tol is missing, it is computed as
max (size (A)) * max (svd (A)) * eps |
See also: null.
Orthogonalize a given column vector x with respect to a set of orthonormal vectors comprising the columns of v using the modified Gram-Schmidt method. On exit, y is a unit vector such that:
norm (y) = 1 v' * y = 0 x = [v, y]*h' |
Return the pseudoinverse of x. Singular values less than tol are ignored.
If the second argument is omitted, it is taken to be
tol = max (size (x)) * sigma_max (x) * eps, |
where sigma_max (x) is the maximal singular value of x.
Compute the rank of matrix A, using the singular value decomposition.
The rank is taken to be the number of singular values of A that are greater than the specified tolerance tol. If the second argument is omitted, it is taken to be
tol = max (size (A)) * sigma(1) * eps; |
where eps is machine precision and sigma(1) is the largest
singular value of A.
The rank of a matrix is the number of linearly independent rows or
columns and determines how many particular solutions exist to a system
of equations. Use null for finding the remaining homogenous
solutions.
Example:
x = [1 2 3
4 5 6
7 8 9];
rank (x)
⇒ 2
|
The number of linearly independent rows is only 2 because the final row is a linear combination of -1*row1 + 2*row2.
Compute the 1-norm estimate of the reciprocal condition number as returned by LAPACK. If the matrix is well-conditioned then c will be near 1 and if the matrix is poorly conditioned it will be close to zero.
The matrix A must not be sparse. If the matrix is sparse then
condest (A) or rcond (full (A)) should be used
instead.
Compute the trace of A, the sum of the elements along the main diagonal.
The implementation is straightforward: sum (diag (A)).
See also: eig.
Return the reduced row echelon form of A. tol defaults
to eps * max (size (A)) * norm (A, inf).
Called with two return arguments, k returns the vector of "bound variables", which are those columns on which elimination has been performed.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Compute the Cholesky factor, R, of the symmetric positive definite matrix A, where
R' * R = A. |
Called with one output argument chol fails if A or S is
not positive definite. With two or more output arguments p flags
whether the matrix was positive definite and chol does not fail. A
zero value indicated that the matrix was positive definite and the R
gives the factorization, and p will have a positive value otherwise.
If called with 3 outputs then a sparsity preserving row/column permutation
is applied to A prior to the factorization. That is R
is the factorization of A(Q,Q) such that
R' * R = Q' * A * Q. |
The sparsity preserving permutation is generally returned as a matrix.
However, given the flag "vector", Q will be returned as a
vector such that
R' * R = A(Q, Q). |
Called with either a sparse or full matrix and using the "lower"
flag, chol returns the lower triangular factorization such that
L * L' = A. |
For full matrices, if the "lower" flag is set only the lower
triangular part of the matrix is used for the factorization, otherwise the
upper triangular part is used.
In general the lower triangular factorization is significantly faster for sparse matrices.
See also: hess, lu, qr, qz, schur, svd, cholinv, chol2inv, cholupdate, cholinsert, choldelete, cholshift.
Use the Cholesky factorization to compute the inverse of the symmetric positive definite matrix A.
Invert a symmetric, positive definite square matrix from its Cholesky
decomposition, U. Note that U should be an upper-triangular
matrix with positive diagonal elements. chol2inv (U)
provides inv (U'*U) but it is much faster than
using inv.
Update or downdate a Cholesky factorization. Given an upper triangular matrix R and a column vector u, attempt to determine another upper triangular matrix R1 such that
"+"
"-"
If op is "-", info is set to
If info is not present, an error message is printed in cases 1 and 2.
See also: chol, cholinsert, choldelete, cholshift.
Given a Cholesky factorization of a real symmetric or complex Hermitian positive definite matrix A = R’*R, R upper triangular, return the Cholesky factorization of A1, where A1(p,p) = A, A1(:,j) = A1(j,:)’ = u and p = [1:j-1,j+1:n+1]. u(j) should be positive. On return, info is set to
If info is not present, an error message is printed in cases 1 and 2.
See also: chol, cholupdate, choldelete, cholshift.
Given a Cholesky factorization of a real symmetric or complex Hermitian positive definite matrix A = R’*R, R upper triangular, return the Cholesky factorization of A(p,p), where p = [1:j-1,j+1:n+1].
See also: chol, cholupdate, cholinsert, cholshift.
Given a Cholesky factorization of a real symmetric or complex Hermitian
positive definite matrix A = R’*R, R upper
triangular, return the Cholesky factorization of
A(p,p), where p is the permutation
p = [1:i-1, shift(i:j, 1), j+1:n] if i < j
or
p = [1:j-1, shift(j:i,-1), i+1:n] if j < i.
See also: chol, cholupdate, cholinsert, choldelete.
Compute the Hessenberg decomposition of the matrix A.
The Hessenberg decomposition is
P * H * P' = A where P is a square
unitary matrix (P' * P = I, using complex-conjugate
transposition) and H is upper Hessenberg
(H(i, j) = 0 forall i >= j+1).
The Hessenberg decomposition is usually used as the first step in an eigenvalue computation, but has other applications as well (see Golub, Nash, and Van Loan, IEEE Transactions on Automatic Control, 1979).
Compute the LU decomposition of A. If A is full
subroutines from
LAPACK are used and if A is sparse then UMFPACK is used. The
result is returned in a permuted form, according to the optional return
value P. For example, given the matrix a = [1, 2; 3, 4],
[l, u, p] = lu (a) |
returns
l = 1.00000 0.00000 0.33333 1.00000 u = 3.00000 4.00000 0.00000 0.66667 p = 0 1 1 0 |
The matrix is not required to be square.
When called with two or three output arguments and a spare input matrix,
lu does not attempt to perform sparsity preserving column
permutations. Called with a fourth output argument, the sparsity
preserving column transformation Q is returned, such that
P * A * Q = L * U.
Called with a fifth output argument and a sparse input matrix,
lu attempts to use a scaling factor R on the input matrix
such that
P * (R \ A) * Q = L * U.
This typically leads to a sparser and more stable factorization.
An additional input argument thres, that defines the pivoting
threshold can be given. thres can be a scalar, in which case
it defines the UMFPACK pivoting tolerance for both symmetric and
unsymmetric cases. If thres is a 2-element vector, then the first
element defines the pivoting tolerance for the unsymmetric UMFPACK
pivoting strategy and the second for the symmetric strategy. By default,
the values defined by spparms are used ([0.1, 0.001]).
Given the string argument "vector", lu returns the values
of P and Q as vector values, such that for full matrix,
A (P,:) = L * U, and R(P,:)
* A (:, Q) = L * U.
With two output arguments, returns the permuted forms of the upper and
lower triangular matrices, such that A = L * U.
With one output argument y, then the matrix returned by the LAPACK
routines is returned. If the input matrix is sparse then the matrix L
is embedded into U to give a return value similar to the full case.
For both full and sparse matrices, lu loses the permutation
information.
Given an LU factorization of a real or complex matrix
A = L*U, L lower unit trapezoidal and
U upper trapezoidal, return the LU factorization
of A + x*y.’, where x and y are
column vectors (rank-1 update) or matrices with equal number of columns
(rank-k update).
Optionally, row-pivoted updating can be used by supplying
a row permutation (pivoting) matrix P;
in that case, an updated permutation matrix is returned.
Note that if L, U, P is a pivoted LU factorization
as obtained by lu:
[L, U, P] = lu (A); |
then a factorization of A+x*y.' can be obtained
either as
[L1, U1] = lu (L, U, P*x, y) |
or
[L1, U1, P1] = lu (L, U, P, x, y) |
The first form uses the unpivoted algorithm, which is faster, but less stable. The second form uses a slower pivoted algorithm, which is more stable.
The matrix case is done as a sequence of rank-1 updates; thus, for large enough k, it will be both faster and more accurate to recompute the factorization from scratch.
See also: lu, cholupdate, qrupdate.
Compute the QR factorization of A, using standard LAPACK
subroutines. For example, given the matrix A = [1, 2; 3, 4],
[Q, R] = qr (A) |
returns
Q = -0.31623 -0.94868 -0.94868 0.31623 R = -3.16228 -4.42719 0.00000 -0.63246 |
The qr factorization has applications in the solution of least
squares problems
min norm(A x - b) |
for overdetermined systems of equations (i.e.,
A
is a tall, thin matrix). The QR factorization is
Q * R = A where Q is an orthogonal matrix and
R is upper triangular.
If given a second argument of '0', qr returns an economy-sized
QR factorization, omitting zero rows of R and the corresponding
columns of Q.
If the matrix A is full, the permuted QR factorization
[Q, R, P] = qr (A) forms the
QR factorization such that the diagonal entries of R are
decreasing in magnitude order. For example, given the matrix a = [1,
2; 3, 4],
[Q, R, P] = qr (A) |
returns
Q = -0.44721 -0.89443 -0.89443 0.44721 R = -4.47214 -3.13050 0.00000 0.44721 P = 0 1 1 0 |
The permuted qr factorization [Q, R, P] = qr
(A) factorization allows the construction of an orthogonal basis of
span (A).
If the matrix A is sparse, then compute the sparse
QR factorization of A, using CSPARSE. As the matrix Q
is in general a full matrix, this function returns the Q-less
factorization R of A, such that R = chol (A' *
A).
If the final argument is the scalar 0 and the number of rows is
larger than the number of columns, then an economy factorization is
returned. That is R will have only size (A,1) rows.
If an additional matrix B is supplied, then qr returns
C, where C = Q' * B. This allows the
least squares approximation of A \ B to be calculated
as
[C, R] = qr (A, B) x = R \ C |
See also: chol, hess, lu, qz, schur, svd, qrupdate, qrinsert, qrdelete, qrshift.
Given a QR factorization of a real or complex matrix A = Q*R, Q unitary and R upper trapezoidal, return the QR factorization of A + u*v’, where u and v are column vectors (rank-1 update) or matrices with equal number of columns (rank-k update). Notice that the latter case is done as a sequence of rank-1 updates; thus, for k large enough, it will be both faster and more accurate to recompute the factorization from scratch.
The QR factorization supplied may be either full (Q is square) or economized (R is square).
Given a QR factorization of a real or complex matrix
A = Q*R, Q unitary and
R upper trapezoidal, return the QR factorization of
[A(:,1:j-1) x A(:,j:n)], where u is a column vector to be
inserted into A (if orient is "col"), or the
QR factorization of [A(1:j-1,:);x;A(:,j:n)], where x
is a row vector to be inserted into A (if orient is
"row").
The default value of orient is "col".
If orient is "col",
u may be a matrix and j an index vector
resulting in the QR factorization of a matrix B such that
B(:,j) gives u and B(:,j) = [] gives A.
Notice that the latter case is done as a sequence of k insertions;
thus, for k large enough, it will be both faster and more accurate to
recompute the factorization from scratch.
If orient is "col",
the QR factorization supplied may be either full
(Q is square) or economized (R is square).
If orient is "row", full factorization is needed.
Given a QR factorization of a real or complex matrix
A = Q*R, Q unitary and
R upper trapezoidal, return the QR factorization of
[A(:,1:j-1) A(:,j+1:n)], i.e., A with one column deleted
(if orient is "col"), or the QR factorization of
[A(1:j-1,:);A(j+1:n,:)], i.e., A with one row deleted (if
orient is "row").
The default value of orient is "col".
If orient is "col",
j may be an index vector
resulting in the QR factorization of a matrix B such that
A(:,j) = [] gives B.
Notice that the latter case is done as a sequence of k deletions;
thus, for k large enough, it will be both faster and more accurate to
recompute the factorization from scratch.
If orient is "col",
the QR factorization supplied may be either full
(Q is square) or economized (R is square).
If orient is "row", full factorization is needed.
Given a QR factorization of a real or complex matrix
A = Q*R, Q unitary and
R upper trapezoidal, return the QR factorization
of A(:,p), where p is the permutation
p = [1:i-1, shift(i:j, 1), j+1:n] if i < j
or
p = [1:j-1, shift(j:i,-1), i+1:n] if j < i.
QZ decomposition of the generalized eigenvalue problem (A x = s B x). There are three ways to call this function:
lambda = qz (A, B)
Computes the generalized eigenvalues lambda of (A - s B).
[AA, BB, Q, Z, V, W, lambda] = qz (A, B)
Computes QZ decomposition, generalized eigenvectors, and generalized eigenvalues of (A - s B)
A * V = B * V * diag (lambda) W' * A = diag (lambda) * W' * B AA = Q * A * Z, BB = Q * B * Z |
with Q and Z orthogonal (unitary)= I
[AA,BB,Z{, lambda}] = qz (A, B, opt)
As in form [2], but allows ordering of generalized eigenpairs for (e.g.) solution of discrete time algebraic Riccati equations. Form 3 is not available for complex matrices, and does not compute the generalized eigenvectors V, W, nor the orthogonal matrix Q.
for ordering eigenvalues of the GEP pencil. The leading block of the revised pencil contains all eigenvalues that satisfy:
"N"= unordered (default)
"S"= small: leading block has all |lambda| ≤ 1
"B"= big: leading block has all |lambda| ≥ 1
"-"= negative real part: leading block has all eigenvalues in the open left half-plane
"+"= non-negative real part: leading block has all eigenvalues in the closed right half-plane
Note: qz performs permutation balancing, but not scaling
(see XREFbalance). The order of output arguments was selected for
compatibility with MATLAB.
See also: eig, balance, lu, chol, hess, qr, qzhess, schur, svd.
Compute the Hessenberg-triangular decomposition of the matrix pencil
(A, B), returning
aa = q * A * z,
bb = q * B * z, with q and z
orthogonal. For example:
[aa, bb, q, z] = qzhess ([1, 2; 3, 4], [5, 6; 7, 8])
⇒ aa = [ -3.02244, -4.41741; 0.92998, 0.69749 ]
⇒ bb = [ -8.60233, -9.99730; 0.00000, -0.23250 ]
⇒ q = [ -0.58124, -0.81373; -0.81373, 0.58124 ]
⇒ z = [ 1, 0; 0, 1 ]
|
The Hessenberg-triangular decomposition is the first step in Moler and Stewart’s QZ decomposition algorithm.
Algorithm taken from Golub and Van Loan, Matrix Computations, 2nd edition.
Compute the Schur decomposition of A
|
where U is a unitary matrix
(U'* U is identity)
and S is upper triangular. The eigenvalues of A (and S)
are the diagonal elements of S. If the matrix A
is real, then the real Schur decomposition is computed, in which the
matrix U is orthogonal and S is block upper triangular
with blocks of size at most
2 x 2
along the diagonal. The diagonal elements of S
(or the eigenvalues of the
2 x 2
blocks, when appropriate) are the eigenvalues of A and S.
The default for real matrices is a real Schur decomposition.
A complex decomposition may be forced by passing the flag
"complex".
The eigenvalues are optionally ordered along the diagonal according to
the value of opt. opt = "a" indicates that all
eigenvalues with negative real parts should be moved to the leading
block of S
(used in are), opt = "d" indicates that all eigenvalues
with magnitude less than one should be moved to the leading block of S
(used in dare), and opt = "u", the default, indicates
that no ordering of eigenvalues should occur. The leading k
columns of U always span the A-invariant
subspace corresponding to the k leading eigenvalues of S.
The Schur decomposition is used to compute eigenvalues of a
square matrix, and has applications in the solution of algebraic
Riccati equations in control (see are and dare).
Convert a real, upper quasi-triangular Schur form TR to a complex, upper triangular Schur form T.
Note that the following relations hold:
UR * TR * UR' = U * T * U' and
U' * U is the identity matrix I.
Note also that U and T are not unique.
See also: schur.
Determine the largest principal angle between two subspaces spanned by the columns of matrices A and B.
Compute the singular value decomposition of A
A = U*S*V' |
The function svd normally returns only the vector of singular values.
When called with three return values, it computes
U, S, and V.
For example,
svd (hilb (3)) |
returns
ans = 1.4083189 0.1223271 0.0026873 |
and
[u, s, v] = svd (hilb (3)) |
returns
u = -0.82704 0.54745 0.12766 -0.45986 -0.52829 -0.71375 -0.32330 -0.64901 0.68867 s = 1.40832 0.00000 0.00000 0.00000 0.12233 0.00000 0.00000 0.00000 0.00269 v = -0.82704 0.54745 0.12766 -0.45986 -0.52829 -0.71375 -0.32330 -0.64901 0.68867 |
If given a second argument, svd returns an economy-sized
decomposition, eliminating the unnecessary rows or columns of U or
V.
Query or set the underlying LAPACK driver used by svd.
Currently recognized values are "gesvd" and "gesdd".
The default is "gesvd".
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: svd.
Compute Householder reflection vector housv to reflect x to be the j-th column of identity, i.e.,
(I - beta*housv*housv')x = norm (x)*e(j) if x(j) < 0, (I - beta*housv*housv')x = -norm (x)*e(j) if x(j) >= 0 |
Inputs
vector
index into vector
threshold for zero (usually should be the number 0)
Outputs (see Golub and Van Loan):
If beta = 0, then no reflection need be applied (zer set to 0)
householder vector
Construct an orthogonal basis u of block Krylov subspace
[v a*v a^2*v … a^(k+1)*v] |
Using Householder reflections to guard against loss of orthogonality.
If V is a vector, then h contains the Hessenberg matrix
such that a*u == u*h+rk*ek', in which rk =
a*u(:,k)-u*h(:,k), and ek' is the vector
[0, 0, …, 1] of length k. Otherwise, h is
meaningless.
If V is a vector and k is greater than
length (A) - 1, then h contains the Hessenberg matrix such
that a*u == u*h.
The value of nu is the dimension of the span of the Krylov subspace (based on eps1).
If b is a vector and k is greater than m-1, then h contains the Hessenberg decomposition of A.
The optional parameter eps1 is the threshold for zero. The default value is 1e-12.
If the optional parameter pflg is nonzero, row pivoting is used to improve numerical behavior. The default value is 0.
Reference: A. Hodel, P. Misra, Partial Pivoting in the Computation of Krylov Subspaces of Large Sparse Systems, Proceedings of the 42nd IEEE Conference on Decision and Control, December 2003.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Return the exponential of a matrix, defined as the infinite Taylor series
expm (A) = I + A + A^2/2! + A^3/3! + … |
The Taylor series is not the way to compute the matrix exponential; see Moler and Van Loan, Nineteen Dubious Ways to Compute the Exponential of a Matrix, SIAM Review, 1978. This routine uses Ward’s diagonal Padé approximation method with three step preconditioning (SIAM Journal on Numerical Analysis, 1977). Diagonal Padé approximations are rational polynomials of matrices
-1 D (A) N (A) |
whose Taylor series matches the first
2q+1
terms of the Taylor series above; direct evaluation of the Taylor series
(with the same preconditioning steps) may be desirable in lieu of the
Padé approximation when
Dq(A)
is ill-conditioned.
Compute the matrix logarithm of the square matrix A. The implementation utilizes a Padé approximant and the identity
logm (A) = 2^k * logm (A^(1 / 2^k)) |
The optional argument opt_iters is the maximum number of square roots to compute and defaults to 100. The optional output iters is the number of square roots actually computed.
Compute the matrix square root of the square matrix A.
Ref: N.J. Higham. A New sqrtm for MATLAB. Numerical Analysis Report No. 336, Manchester Centre for Computational Mathematics, Manchester, England, January 1999.
Form the Kronecker product of two or more matrices, defined block by block as
x = [ a(i,j)*b ] |
For example:
kron (1:4, ones (3, 1))
⇒ 1 2 3 4
1 2 3 4
1 2 3 4
|
If there are more than two input arguments A1, A2, …, An the Kronecker product is computed as
kron (kron (A1, A2), …, An) |
Since the Kronecker product is associative, this is well-defined.
Compute products of matrix blocks. The blocks are given as
2-dimensional subarrays of the arrays A, B.
The size of A must have the form [m,k,…] and
size of B must be [k,n,…]. The result is
then of size [m,n,…] and is computed as follows:
for i = 1:prod (size (A)(3:end)) C(:,:,i) = A(:,:,i) * B(:,:,i) endfor |
Solve the Sylvester equation
A X + X B + C = 0 |
using standard LAPACK subroutines. For example:
syl ([1, 2; 3, 4], [5, 6; 7, 8], [9, 10; 11, 12]) ⇒ [ -0.50000, -0.66667; -0.66667, -0.50000 ] |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Solve A x = b using the Bi-conjugate gradient iterative method.
min (20, numel (b)) is used.
zeros (size (b)) is used.
A can be passed as a matrix or as a function handle or
inline function f such that f(x, "notransp") = A*x
and f(x, "transp") = A'*x.
The preconditioner P is given as P = M1 * M2.
Both M1 and M2 can be passed as a matrix or as
a function handle or inline function g such that
g(x, "notransp") = M1 \ x or g(x, "notransp") = M2 \ x and
g(x, "transp") = M1' \ x or g(x, "transp") = M2' \ x.
If called with more than one output parameter
(the value 2 is unused but skipped for compatibility).
Solve A x = b using the stabilizied Bi-conjugate gradient iterative
method.
min (20, numel (b)) is
used.
zeros (size (b)) is used.
A can be passed as a matrix or as a function handle or
inline function f such that f(x) = A*x.
The preconditioner P is given as P = M1 * M2.
Both M1 and M2 can be passed as a matrix or as a function
handle or inline function g such that g(x) = M1 \ x or
g(x) = M2 \ x.
If called with more than one output parameter
(the value 2 is unused but skipped for compatibility).
Solve A x = b, where A is a square matrix, using the
Conjugate Gradients Squared method.
min (20, numel (b)) is
used.
zeros (size (b)) is used.
A can be passed as a matrix or as a function handle or
inline function f such that f(x) = A*x.
The preconditioner P is given as P = M1 * M2.
Both M1 and M2 can be passed as a matrix or as a function
handle or inline function g such that g(x) = M1 \ x or
g(x) = M2 \ x.
If called with more than one output parameter
(the value 2 is unused but skipped for compatibility).
Solve A x = b using the Preconditioned GMRES iterative method
with restart, a.k.a. PGMRES(m).
min (10, numel (b) / restart) is used.
zeros (size (b)) is used.
numel (b) is used.
Argument A can be passed as a matrix, function handle, or
inline function f such that f(x) = A*x.
The preconditioner P is given as P = M1 * M2.
Both M1 and M2 can be passed as a matrix, function handle, or
inline function g such that g(x) = M1\x or g(x) = M2\x.
Besides the vector x, additional outputs are:
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Vectorization is a programming technique that uses vector operations instead of element-by-element loop-based operations. Besides frequently producing more succinct Octave code, vectorization also allows for better optimization in the subsequent implementation. The optimizations may occur either in Octave’s own Fortran, C, or C++ internal implementation, or even at a lower level depending on the compiler and external numerical libraries used to build Octave. The ultimate goal is to make use of your hardware’s vector instructions if possible or to perform other optimizations in software.
Vectorization is not a concept unique to Octave, but it is particularly important because Octave is a matrix-oriented language. Vectorized Octave code will see a dramatic speed up (10X–100X) in most cases.
This chapter discusses vectorization and other techniques for writing faster code.
| 19.1 Basic Vectorization | Basic techniques for code optimization | |
| 19.2 Broadcasting | Broadcasting operations | |
| 19.3 Function Application | Applying functions to arrays, cells, and structs | |
| 19.4 Accumulation | Accumulation functions | |
| 19.5 JIT Compiler | Just-In-Time Compiler for loops | |
| 19.6 Miscellaneous Techniques | Other techniques for speeding up code | |
| 19.7 Examples |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
To a very good first approximation, the goal in vectorization is to write code that avoids loops and uses whole-array operations. As a trivial example, consider
for i = 1:n
for j = 1:m
c(i,j) = a(i,j) + b(i,j);
endfor
endfor
|
compared to the much simpler
c = a + b; |
This isn’t merely easier to write; it is also internally much easier to optimize. Octave delegates this operation to an underlying implementation which, among other optimizations, may use special vector hardware instructions or could conceivably even perform the additions in parallel. In general, if the code is vectorized, the underlying implementation has more freedom about the assumptions it can make in order to achieve faster execution.
This is especially important for loops with "cheap" bodies. Often it suffices to vectorize just the innermost loop to get acceptable performance. A general rule of thumb is that the "order" of the vectorized body should be greater or equal to the "order" of the enclosing loop.
As a less trivial example, instead of
for i = 1:n-1 a(i) = b(i+1) - b(i); endfor |
write
a = b(2:n) - b(1:n-1); |
This shows an important general concept about using arrays for indexing instead of looping over an index variable. See section Index Expressions. Also use boolean indexing generously. If a condition needs to be tested, this condition can also be written as a boolean index. For instance, instead of
for i = 1:n
if (a(i) > 5)
a(i) -= 20
endif
endfor
|
write
a(a>5) -= 20; |
which exploits the fact that a > 5 produces a boolean index.
Use elementwise vector operators whenever possible to avoid looping
(operators like .* and .^). See section Arithmetic Operators. For
simple inline functions, the vectorize function can do this
automatically.
Create a vectorized version of the inline function fun
by replacing all occurrences of *, /, etc., with
.*, ./, etc.
This may be useful, for example, when using inline functions with numerical integration or optimization where a vector-valued function is expected.
fcn = vectorize (inline ("x^2 - 1"))
⇒ fcn = f(x) = x.^2 - 1
quadv (fcn, 0, 3)
⇒ 6
|
Also exploit broadcasting in these elementwise operators both to avoid looping and unnecessary intermediate memory allocations. See section Broadcasting.
Use built-in and library functions if possible. Built-in and compiled functions are very fast. Even with an m-file library function, chances are good that it is already optimized, or will be optimized more in a future release.
For instance, even better than
a = b(2:n) - b(1:n-1); |
is
a = diff (b); |
Most Octave functions are written with vector and array arguments in mind. If you find yourself writing a loop with a very simple operation, chances are that such a function already exists. The following functions occur frequently in vectorized code:
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Broadcasting refers to how Octave binary operators and functions behave when their matrix or array operands or arguments differ in size. Since version 3.6.0, Octave now automatically broadcasts vectors, matrices, and arrays when using elementwise binary operators and functions. Broadly speaking, smaller arrays are “broadcast” across the larger one, until they have a compatible shape. The rule is that corresponding array dimensions must either
In case all dimensions are equal, no broadcasting occurs and ordinary element-by-element arithmetic takes place. For arrays of higher dimensions, if the number of dimensions isn’t the same, then missing trailing dimensions are treated as 1. When one of the dimensions is 1, the array with that singleton dimension gets copied along that dimension until it matches the dimension of the other array. For example, consider
x = [1 2 3;
4 5 6;
7 8 9];
y = [10 20 30];
x + y
|
Without broadcasting, x + y would be an error because the dimensions
do not agree. However, with broadcasting it is as if the following
operation were performed:
x = [1 2 3
4 5 6
7 8 9];
y = [10 20 30
10 20 30
10 20 30];
x + y
⇒ 11 22 33
14 25 36
17 28 39
|
That is, the smaller array of size [1 3] gets copied along the
singleton dimension (the number of rows) until it is [3 3]. No
actual copying takes place, however. The internal implementation reuses
elements along the necessary dimension in order to achieve the desired
effect without copying in memory.
Both arrays can be broadcast across each other, for example, all pairwise differences of the elements of a vector with itself:
y - y'
⇒ 0 10 20
-10 0 10
-20 -10 0
|
Here the vectors of size [1 3] and [3 1] both get
broadcast into matrices of size [3 3] before ordinary matrix
subtraction takes place.
A special case of broadcasting that may be familiar is when all
dimensions of the array being broadcast are 1, i.e., the array is a
scalar. Thus for example, operations like x - 42 and max
(x, 2) are basic examples of broadcasting.
For a higher-dimensional example, suppose img is an RGB image of
size [m n 3] and we wish to multiply each color by a different
scalar. The following code accomplishes this with broadcasting,
img .*= permute ([0.8, 0.9, 1.2], [1, 3, 2]); |
Note the usage of permute to match the dimensions of the
[0.8, 0.9, 1.2] vector with img.
For functions that are not written with broadcasting semantics,
bsxfun can be useful for coercing them to broadcast.
The binary singleton expansion function applier performs broadcasting, that is, applies a binary function f element-by-element to two array arguments A and B, and expands as necessary singleton dimensions in either input argument. f is a function handle, inline function, or string containing the name of the function to evaluate. The function f must be capable of accepting two column-vector arguments of equal length, or one column vector argument and a scalar.
The dimensions of A and B must be equal or singleton. The singleton dimensions of the arrays will be expanded to the same dimensionality as the other array.
Broadcasting is only applied if either of the two broadcasting conditions hold. As usual, however, broadcasting does not apply when two dimensions differ and neither is 1:
x = [1 2 3
4 5 6];
y = [10 20
30 40];
x + y
|
This will produce an error about nonconformant arguments.
Besides common arithmetic operations, several functions of two arguments also broadcast. The full list of functions and operators that broadcast is
plus + .+
minus - .-
times .*
rdivide ./
ldivide .\
power .^ .**
lt <
le <=
eq ==
gt >
ge >=
ne != ~=
and &
or |
atan2
hypot
max
min
mod
rem
xor
+= -= .+= .-= .*= ./= .\= .^= .**= &= |=
|
Beware of resorting to broadcasting if a simpler operation will suffice. For matrices a and b, consider the following:
c = sum (permute (a, [1, 3, 2]) .* permute (b, [3, 2, 1]), 3); |
This operation broadcasts the two matrices with permuted dimensions
across each other during elementwise multiplication in order to obtain a
larger 3-D array, and this array is then summed along the third dimension.
A moment of thought will prove that this operation is simply the much
faster ordinary matrix multiplication, c = a*b;.
A note on terminology: “broadcasting” is the term popularized by the
Numpy numerical environment in the Python programming language. In other
programming languages and environments, broadcasting may also be known
as binary singleton expansion (BSX, in MATLAB, and the
origin of the name of the bsxfun function), recycling (R
programming language), single-instruction multiple data (SIMD),
or replication.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The new broadcasting semantics almost never affect code that worked in previous versions of Octave. Consequently, all code inherited from MATLAB that worked in previous versions of Octave should still work without change in Octave. The only exception is code such as
try c = a.*b; catch c = a.*a; end_try_catch |
that may have relied on matrices of different size producing an error. Due to how broadcasting changes semantics with older versions of Octave, by default Octave warns if a broadcasting operation is performed. To disable this warning, refer to its ID (see warning_ids):
warning ("off", "Octave:broadcast");
|
If you want to recover the old behavior and produce an error, turn this warning into an error:
warning ("error", "Octave:broadcast");
|
For broadcasting on scalars that worked in previous versions of Octave, this warning will not be emitted.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
As a general rule, functions should already be written with matrix arguments in mind and should consider whole matrix operations in a vectorized manner. Sometimes, writing functions in this way appears difficult or impossible for various reasons. For those situations, Octave provides facilities for applying a function to each element of an array, cell, or struct.
Execute a function on each element of an array. This is useful for functions that do not accept array arguments. If the function does accept array arguments it is better to call the function directly.
The first input argument func can be a string, a function
handle, an inline function, or an anonymous function. The input
argument A can be a logic array, a numeric array, a string
array, a structure array, or a cell array. By a call of the function
arrayfun all elements of A are passed on to the named
function func individually.
The named function can also take more than two input arguments, with the input arguments given as third input argument b, fourth input argument c, … If given more than one array input argument then all input arguments must have the same sizes, for example:
arrayfun (@atan2, [1, 0], [0, 1])
⇒ [ 1.5708 0.0000 ]
|
If the parameter val after a further string input argument
"UniformOutput" is set true (the default), then the named
function func must return a single element which then will be
concatenated into the return value and is of type matrix. Otherwise,
if that parameter is set to false, then the outputs are
concatenated in a cell array. For example:
arrayfun (@(x,y) x:y, "abc", "def", "UniformOutput", false)
⇒
{
[1,1] = abcd
[1,2] = bcde
[1,3] = cdef
}
|
If more than one output arguments are given then the named function must return the number of return values that also are expected, for example:
[A, B, C] = arrayfun (@find, [10; 0], "UniformOutput", false)
⇒
A =
{
[1,1] = 1
[2,1] = [](0x0)
}
B =
{
[1,1] = 1
[2,1] = [](0x0)
}
C =
{
[1,1] = 10
[2,1] = [](0x0)
}
|
If the parameter errfunc after a further string input argument
"ErrorHandler" is another string, a function handle, an inline
function, or an anonymous function, then errfunc defines a
function to call in the case that func generates an error.
The definition of the function must be of the form
function […] = errfunc (s, …) |
where there is an additional input argument to errfunc
relative to func, given by s. This is a structure with
the elements "identifier", "message", and
"index" giving, respectively, the error identifier, the error
message, and the index of the array elements that caused the error. The
size of the output argument of errfunc must have the same size as the
output argument of func, otherwise a real error is thrown. For
example:
function y = ferr (s, x), y = "MyString"; endfunction
arrayfun (@str2num, [1234],
"UniformOutput", false, "ErrorHandler", @ferr)
⇒
{
[1,1] = MyString
}
|
Compute f(S) for the non-zero values of S.
This results in a sparse matrix with the same structure as
S. The function f can be passed as a string, a
function handle, or an inline function.
Evaluate the function named name on the elements of the cell array C. Elements in C are passed on to the named function individually. The function name can be one of the functions
isemptyReturn 1 for empty elements.
islogicalReturn 1 for logical elements.
isnumericReturn 1 for numeric elements.
isrealReturn 1 for real elements.
lengthReturn a vector of the lengths of cell elements.
ndimsReturn the number of dimensions of each element.
numelprodofsizeReturn the number of elements contained within each cell element. The number is the product of the dimensions of the object at each cell element.
sizeReturn the size along the k-th dimension.
isclassReturn 1 for elements of class.
Additionally, cellfun accepts an arbitrary function func
in the form of an inline function, function handle, or the name of a
function (in a character string). The function can take one or more arguments,
with the inputs arguments given by C, D, etc. Equally the
function can return one or more output arguments. For example:
cellfun ("atan2", {1, 0}, {0, 1})
⇒ [ 1.57080 0.00000 ]
|
The number of output arguments of cellfun matches the number of output
arguments of the function. The outputs of the function will be collected
into the output arguments of cellfun like this:
function [a, b] = twoouts (x)
a = x;
b = x*x;
endfunction
[aa, bb] = cellfun (@twoouts, {1, 2, 3})
⇒
aa =
1 2 3
bb =
1 4 9
|
Note that per default the output argument(s) are arrays of the same size as the input arguments. Input arguments that are singleton (1x1) cells will be automatically expanded to the size of the other arguments.
If the parameter "UniformOutput" is set to true (the default),
then the function must return scalars which will be concatenated into the
return array(s). If "UniformOutput" is false, the outputs are
concatenated into a cell array (or cell arrays). For example:
cellfun ("tolower", {"Foo", "Bar", "FooBar"},
"UniformOutput", false)
⇒ {"foo", "bar", "foobar"}
|
Given the parameter "ErrorHandler", then errfunc defines a
function to call in case func generates an error. The form of the
function is
function […] = errfunc (s, …) |
where there is an additional input argument to errfunc relative to
func, given by s. This is a structure with the elements
"identifier", "message" and "index", giving
respectively the error identifier, the error message, and the index into the
input arguments of the element that caused the error. For example:
function y = foo (s, x), y = NaN; endfunction
cellfun ("factorial", {-1,2}, "ErrorHandler", @foo)
⇒ [NaN 2]
|
Use cellfun intelligently. The cellfun function is a
useful tool for avoiding loops. It is often used with anonymous
function handles; however, calling an anonymous function involves an
overhead quite comparable to the overhead of an m-file function.
Passing a handle to a built-in function is faster, because the
interpreter is not involved in the internal loop. For example:
a = {…}
v = cellfun (@(x) det (x), a); # compute determinants
v = cellfun (@det, a); # faster
|
Evaluate the function named name on the fields of the structure S. The fields of S are passed to the function func individually.
structfun accepts an arbitrary function func in the form of
an inline function, function handle, or the name of a function (in a
character string). In the case of a character string argument, the
function must accept a single argument named x, and it must return
a string value. If the function returns more than one argument, they are
returned as separate output variables.
If the parameter "UniformOutput" is set to true (the default),
then the function must return a single element which will be concatenated
into the return value. If "UniformOutput" is false, the outputs
are placed into a structure with the same fieldnames as the input
structure.
s.name1 = "John Smith";
s.name2 = "Jill Jones";
structfun (@(x) regexp (x, '(\w+)$', "matches"){1}, s,
"UniformOutput", false)
⇒
{
name1 = Smith
name2 = Jones
}
|
Given the parameter "ErrorHandler", errfunc defines a
function to call in case func generates an error. The form of the
function is
function […] = errfunc (se, …) |
where there is an additional input argument to errfunc relative to
func, given by se. This is a structure with the
elements "identifier", "message" and "index",
giving respectively the error identifier, the error message, and the index
into the input arguments of the element that caused the error. For an
example on how to use an error handler, see cellfun.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Whenever it’s possible to categorize according to indices the elements of an array when performing a computation, accumulation functions can be useful.
Create an array by accumulating the elements of a vector into the positions defined by their subscripts. The subscripts are defined by the rows of the matrix subs and the values by vals. Each row of subs corresponds to one of the values in vals. If vals is a scalar, it will be used for each of the row of subs. If subs is a cell array of vectors, all vectors must be of the same length, and the subscripts in the kth vector must correspond to the kth dimension of the result.
The size of the matrix will be determined by the subscripts themselves. However, if sz is defined it determines the matrix size. The length of sz must correspond to the number of columns in subs. An exception is if subs has only one column, in which case sz may be the dimensions of a vector and the subscripts of subs are taken as the indices into it.
The default action of accumarray is to sum the elements with
the same subscripts. This behavior can be modified by defining the
func function. This should be a function or function handle
that accepts a column vector and returns a scalar. The result of the
function should not depend on the order of the subscripts.
The elements of the returned array that have no subscripts associated
with them are set to zero. Defining fillval to some other value
allows these values to be defined. This behavior changes, however,
for certain values of func. If func is min
(respectively, max) then the result will be filled with the
minimum (respectively, maximum) integer if vals is of integral
type, logical false (respectively, logical true) if vals is of
logical type, zero if fillval is zero and all values are
non-positive (respectively, non-negative), and NaN otherwise.
By default accumarray returns a full matrix. If
issparse is logically true, then a sparse matrix is returned
instead.
The following accumarray example constructs a frequency table
that in the first column counts how many occurrences each number in
the second column has, taken from the vector x. Note the usage
of unique for assigning to all repeated elements of x
the same index (see unique).
x = [91, 92, 90, 92, 90, 89, 91, 89, 90, 100, 100, 100];
[u, ~, j] = unique (x);
[accumarray(j', 1), u']
⇒ 2 89
3 90
2 91
2 92
3 100
|
Another example, where the result is a multi-dimensional 3-D array and the default value (zero) appears in the output:
accumarray ([1, 1, 1;
2, 1, 2;
2, 3, 2;
2, 1, 2;
2, 3, 2], 101:105)
⇒ ans(:,:,1) = [101, 0, 0; 0, 0, 0]
⇒ ans(:,:,2) = [0, 0, 0; 206, 0, 208]
|
The sparse option can be used as an alternative to the sparse
constructor (see sparse). Thus
sparse (i, j, sv) |
can be written with accumarray as
accumarray ([i, j], sv', [], [], 0, true) |
For repeated indices, sparse adds the corresponding value. To
take the minimum instead, use min as an accumulator function:
accumarray ([i, j], sv', [], @min, 0, true) |
The complexity of accumarray in general for the non-sparse case is
generally O(M+N), where N is the number of subscripts and M is the
maximum subscript (linearized in multi-dimensional case). If
func is one of @sum (default), @max,
@min or @(x) {x}, an optimized code path is used.
Note that for general reduction function the interpreter overhead can
play a major part and it may be more efficient to do multiple
accumarray calls and compute the results in a vectorized manner.
Create an array by accumulating the slices of an array into the
positions defined by their subscripts along a specified dimension.
The subscripts are defined by the index vector subs.
The dimension is specified by dim. If not given, it defaults
to the first non-singleton dimension. The length of subs must
be equal to size (vals, dim).
The extent of the result matrix in the working dimension will be determined by the subscripts themselves. However, if n is defined it determines this extent.
The default action of accumdim is to sum the subarrays with the
same subscripts. This behavior can be modified by defining the
func function. This should be a function or function handle
that accepts an array and a dimension, and reduces the array along
this dimension. As a special exception, the built-in min and
max functions can be used directly, and accumdim
accounts for the middle empty argument that is used in their calling.
The slices of the returned array that have no subscripts associated with them are set to zero. Defining fillval to some other value allows these values to be defined.
An example of the use of accumdim is:
accumdim ([1, 2, 1, 2, 1], [ 7, -10, 4;
-5, -12, 8;
-12, 2, 8;
-10, 9, -3;
-5, -3, -13])
⇒ [-10,-11,-1;-15,-3,5]
|
See also: accumarray.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Vectorization is the preferred technique for eliminating loops and speeding up code. Nevertheless, it is not always possible to replace every loop. In such situations it may be worth trying Octave’s experimental Just-In-Time (JIT) compiler.
A JIT compiler works by analyzing the body of a loop, translating the Octave statements into another language, compiling the new code segment into an executable, and then running the executable and collecting any results. The process is not simple and there is a significant amount of work to perform for each step. It can still make sense, however, if the number of loop iterations is large. Because Octave is an interpreted language every time through a loop Octave must parse the statements in the loop body before executing them. With a JIT compiler this is done just once when the body is translated to another language.
The JIT compiler is a very new feature in Octave and not all valid Octave
statements can currently be accelerated. However, if no other technique
is available it may be worth benchmarking the code with JIT enabled. The
function jit_enable is used to turn compilation on or off. The
function jit_startcnt sets the threshold for acceleration. Loops
with iteration counts above jit_startcnt will be accelerated. The
function debug_jit is not likely to be of use to anyone not working
directly on the implementation of the JIT compiler.
Query or set the internal variable that enables Octave’s JIT compiler.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: jit_startcnt, debug_jit.
Query or set the internal variable that determines whether JIT compilation will take place for a specific loop. Because compilation is a costly operation it does not make sense to employ JIT when the loop count is low. By default only loops with greater than 1000 iterations will be accelerated.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: jit_enable, debug_jit.
Query or set the internal variable that determines whether debugging/tracing is enabled for Octave’s JIT compiler.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: jit_enable, jit_startcnt.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Here are some other ways of improving the execution speed of Octave programs.
a = zeros (1000); # create a 1000x1000 matrix b = a; # no copying done here b(1) = 1; # copying done here |
Lazy copying applies to whole Octave objects such as matrices, cells, struct, and also individual cell or struct elements (not array elements).
Additionally, index expressions also use lazy copying when Octave can determine that the indexed portion is contiguous in memory. For example:
a = zeros (1000); # create a 1000x1000 matrix b = a(:,10:100); # no copying done here b = a(10:100,:); # copying done here |
This applies to arrays (matrices), cell arrays, and structs indexed
using ‘()’. Index expressions generating comma-separated lists can also
benefit from shallow copying in some cases. In particular, when a is a
struct array, expressions like {a.x}, {a(:,2).x} will use lazy
copying, so that data can be shared between a struct array and a cell array.
Most indexing expressions do not live longer than their parent objects. In rare cases, however, a lazily copied slice outlasts its parent, in which case it becomes orphaned, still occupying unnecessarily more memory than needed. To provide a remedy working in most real cases, Octave checks for orphaned lazy slices at certain situations, when a value is stored into a "permanent" location, such as a named variable or cell or struct element, and possibly economizes them. For example:
a = zeros (1000); # create a 1000x1000 matrix
b = a(:,10:100); # lazy slice
a = []; # the original "a" array is still allocated
c{1} = b; # b is reallocated at this point
|
result = zeros (big_n, big_m) for i = over:and_over ridx = … cidx = … result(ridx, cidx) = new_value (); endfor |
instead of
result = []; for i = ever:and_ever result = [ result, new_value() ]; endfor |
Sometimes the number of items can not be computed in advance, and stack-like operations are needed. When elements are being repeatedly inserted or removed from the end of an array, Octave detects it as stack usage and attempts to use a smarter memory management strategy by pre-allocating the array in bigger chunks. This strategy is also applied to cell and struct arrays.
a = []; while (condition) … a(end+1) = value; # "push" operation … a(end) = []; # "pop" operation … endwhile |
eval or feval excessively.
Parsing input or looking up the name of a function in the symbol table are
relatively expensive operations.
If you are using eval merely as an exception handling mechanism, and not
because you need to execute some arbitrary text, use the try
statement instead. See section The try Statement.
ignore_function_time_stamp when appropriate.
If you are calling lots of functions, and none of them will need to change
during your run, set the variable ignore_function_time_stamp to
"all". This will stop Octave from checking the time stamp of a function
file to see if it has been updated while the program is being run.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following are examples of vectorization questions asked by actual users of Octave and their solutions.
A, the following loop
n = length (A); B = zeros (n, 2); for i = 1:length (A) ## this will be two columns, the first is the difference and ## the second the mean of the two elements used for the diff. B(i,:) = [A(i+1)-A(i), (A(i+1) + A(i))/2)]; endfor |
can be turned into the following one-liner:
B = [diff(A)(:), 0.5*(A(1:end-1)+A(2:end))(:)] |
Note the usage of colon indexing to flatten an intermediate result into a column vector. This is a common vectorization trick.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 20.1 Solvers | ||
| 20.2 Minimizers |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave can solve sets of nonlinear equations of the form
F (x) = 0 |
using the function fsolve, which is based on the MINPACK
subroutine hybrd. This is an iterative technique so a starting
point must be provided. This also has the consequence that
convergence is not guaranteed even if a solution exists.
Solve a system of nonlinear equations defined by the function fcn.
fcn should accept a vector (array) defining the unknown variables,
and return a vector of left-hand sides of the equations. Right-hand sides
are defined to be zeros.
In other words, this function attempts to determine a vector x such
that fcn (x) gives (approximately) all zeros.
x0 determines a starting guess. The shape of x0 is preserved
in all calls to fcn, but otherwise it is treated as a column vector.
options is a structure specifying additional options.
Currently, fsolve recognizes these options:
"FunValCheck", "OutputFcn", "TolX",
"TolFun", "MaxIter", "MaxFunEvals",
"Jacobian", "Updating", "ComplexEqn"
"TypicalX", "AutoScaling" and "FinDiffType".
If "Jacobian" is "on", it specifies that fcn,
called with 2 output arguments, also returns the Jacobian matrix
of right-hand sides at the requested point. "TolX" specifies
the termination tolerance in the unknown variables, while
"TolFun" is a tolerance for equations. Default is 1e-7
for both "TolX" and "TolFun".
If "AutoScaling" is on, the variables will be automatically scaled
according to the column norms of the (estimated) Jacobian. As a result,
TolF becomes scaling-independent. By default, this option is off, because
it may sometimes deliver unexpected (though mathematically correct) results.
If "Updating" is "on", the function will attempt to use
Broyden updates to update the Jacobian, in order to reduce the
amount of Jacobian calculations. If your user function always calculates the
Jacobian (regardless of number of output arguments), this option provides
no advantage and should be set to false.
"ComplexEqn" is "on", fsolve will attempt to solve
complex equations in complex variables, assuming that the equations possess a
complex derivative (i.e., are holomorphic). If this is not what you want,
should unpack the real and imaginary parts of the system to get a real
system.
For description of the other options, see optimset.
On return, fval contains the value of the function fcn evaluated at x, and info may be one of the following values:
Converged to a solution point. Relative residual error is less than specified by TolFun.
Last relative step size was less that TolX.
Last relative decrease in residual was less than TolF.
Iteration limit exceeded.
The trust region radius became excessively small.
Note: If you only have a single nonlinear equation of one variable, using
fzero is usually a much better idea.
Note about user-supplied Jacobians: As an inherent property of the algorithm, Jacobian is always requested for a solution vector whose residual vector is already known, and it is the last accepted successful step. Often this will be one of the last two calls, but not always. If the savings by reusing intermediate results from residual calculation in Jacobian calculation are significant, the best strategy is to employ OutputFcn: After a vector is evaluated for residuals, if OutputFcn is called with that vector, then the intermediate results should be saved for future Jacobian evaluation, and should be kept until a Jacobian evaluation is requested or until OutputFcn is called with a different vector, in which case they should be dropped in favor of this most recent vector. A short example how this can be achieved follows:
function [fvec, fjac] = user_func (x, optimvalues, state)
persistent sav = [], sav0 = [];
if (nargin == 1)
## evaluation call
if (nargout == 1)
sav0.x = x; # mark saved vector
## calculate fvec, save results to sav0.
elseif (nargout == 2)
## calculate fjac using sav.
endif
else
## outputfcn call.
if (all (x == sav0.x))
sav = sav0;
endif
## maybe output iteration status, etc.
endif
endfunction
## …
fsolve (@user_func, x0, optimset ("OutputFcn", @user_func, …))
|
The following is a complete example. To solve the set of equations
-2x^2 + 3xy + 4 sin(y) = 6 3x^2 - 2xy^2 + 3 cos(x) = -4 |
you first need to write a function to compute the value of the given function. For example:
function y = f (x) y = zeros (2, 1); y(1) = -2*x(1)^2 + 3*x(1)*x(2) + 4*sin(x(2)) - 6; y(2) = 3*x(1)^2 - 2*x(1)*x(2)^2 + 3*cos(x(1)) + 4; endfunction |
Then, call fsolve with a specified initial condition to find the
roots of the system of equations. For example, given the function
f defined above,
[x, fval, info] = fsolve (@f, [1; 2]) |
results in the solution
x = 0.57983 2.54621 fval = -5.7184e-10 5.5460e-10 info = 1 |
A value of info = 1 indicates that the solution has converged.
When no Jacobian is supplied (as in the example above) it is approximated numerically. This requires more function evaluations, and hence is less efficient. In the example above we could compute the Jacobian analytically as
function [y, jac] = f (x)
y = zeros (2, 1);
y(1) = -2*x(1)^2 + 3*x(1)*x(2) + 4*sin(x(2)) - 6;
y(2) = 3*x(1)^2 - 2*x(1)*x(2)^2 + 3*cos(x(1)) + 4;
if (nargout == 2)
jac = zeros (2, 2);
jac(1,1) = 3*x(2) - 4*x(1);
jac(1,2) = 4*cos(x(2)) + 3*x(1);
jac(2,1) = -2*x(2)^2 - 3*sin(x(1)) + 6*x(1);
jac(2,2) = -4*x(1)*x(2);
endif
endfunction
|
The Jacobian can then be used with the following call to fsolve:
[x, fval, info] = fsolve (@f, [1; 2], optimset ("jacobian", "on"));
|
which gives the same solution as before.
Find a zero of a univariate function.
fun is a function handle, inline function, or string containing the name of the function to evaluate. x0 should be a two-element vector specifying two points which bracket a zero. In other words, there must be a change in sign of the function between x0(1) and x0(2). More mathematically, the following must hold
sign (fun(x0(1))) * sign (fun(x0(2))) <= 0 |
If x0 is a single scalar then several nearby and distant
values are probed in an attempt to obtain a valid bracketing. If this
is not successful, the function fails.
options is a structure specifying additional options.
Currently, fzero
recognizes these options: "FunValCheck", "OutputFcn",
"TolX", "MaxIter", "MaxFunEvals".
For a description of these options, see optimset.
On exit, the function returns x, the approximate zero point and fval, the function value thereof. info is an exit flag that can have these values:
output is a structure containing runtime information about the
fzero algorithm. Fields in the structure are:
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Often it is useful to find the minimum value of a function rather than just
the zeroes where it crosses the x-axis. fminbnd is designed for the
simpler, but very common, case of a univariate function where the interval
to search is bounded. For unbounded minimization of a function with
potentially many variables use fminunc or fminsearch. The two
functions use different internal algorithms and some knowledge of the objective
function is required. For functions which can be differentiated, fminunc
is appropriate. For functions with discontinuities, or for which a gradient
search would fail, use fminsearch. See section Optimization, for
minimization with the presence of constraint functions. Note that searches
can be made for maxima by simply inverting the objective function
(Fto_max = -Fto_min).
Find a minimum point of a univariate function.
fun should be a function handle or name. a, b specify a
starting interval. options is a structure specifying additional
options. Currently, fminbnd recognizes these options:
"FunValCheck", "OutputFcn", "TolX",
"MaxIter", "MaxFunEvals". For a description of these
options, see optimset.
On exit, the function returns x, the approximate minimum point and fval, the function value thereof. info is an exit flag that can have these values:
Notes: The search for a minimum is restricted to be in the interval
bound by a and b. If you only have an initial point
to begin searching from you will need to use an unconstrained
minimization algorithm such as fminunc or fminsearch.
fminbnd internally uses a Golden Section search strategy.
See also: fzero, fminunc, fminsearch, optimset.
Solve an unconstrained optimization problem defined by the function fcn.
fcn should accept a vector (array) defining the unknown variables,
and return the objective function value, optionally with gradient.
fminunc attempts to determine a vector x such that
fcn (x) is a local minimum. x0 determines a
starting guess. The shape of x0 is preserved in all calls to
fcn, but otherwise is treated as a column vector.
options is a structure specifying additional options.
Currently, fminunc recognizes these options:
"FunValCheck", "OutputFcn", "TolX",
"TolFun", "MaxIter", "MaxFunEvals",
"GradObj", "FinDiffType",
"TypicalX", "AutoScaling".
If "GradObj" is "on", it specifies that fcn,
when called with 2 output arguments, also returns the Jacobian matrix
of partial first derivatives at the requested point.
TolX specifies the termination tolerance for the unknown variables
x, while TolFun is a tolerance for the objective function
value fval. The default is 1e-7 for both options.
For a description of the other options, see optimset.
On return, x is the location of the minimum and fval contains the value of the objective function at x. info may be one of the following values:
Converged to a solution point. Relative gradient error is less than
specified by TolFun.
Last relative step size was less than TolX.
Last relative change in function value was less than TolFun.
Iteration limit exceeded—either maximum numer of algorithm iterations
MaxIter or maximum number of function evaluations MaxFunEvals.
Alogrithm terminated by OutputFcn.
The trust region radius became excessively small.
Optionally, fminunc can return a structure with convergence statistics
(output), the output gradient (grad) at the solution x,
and approximate Hessian (hess) at the solution x.
Notes: If have only a single nonlinear equation of one variable then using
fminbnd is usually a much better idea. The algorithm used is a
gradient search which depends on the objective function being differentiable.
If the function has discontinuities it may be better to use a derivative-free
algorithm such as fminsearch.
See also: fminbnd, fminsearch, optimset.
Find a value of x which minimizes the function fun.
The search begins at the point x0 and iterates using the
Nelder & Mead Simplex algorithm (a derivative-free method). This algorithm
is better-suited to functions which have discontinuities or for which
a gradient-based search such as fminunc fails.
Options for the search are provided in the parameter options using
the function optimset. Currently, fminsearch accepts the
options: "TolX", "MaxFunEvals", "MaxIter",
"Display". For a description of these options, see
optimset.
On exit, the function returns x, the minimum point, and fval, the function value thereof.
Example usages:
fminsearch (@(x) (x(1)-5).^2+(x(2)-8).^4, [0;0])
fminsearch (inline ("(x(1)-5).^2+(x(2)-8).^4", "x"), [0;0])
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 21.1 Creating and Manipulating Diagonal/Permutation Matrices | Creation and Manipulation of Diagonal/Permutation Matrices | |
| 21.2 Linear Algebra with Diagonal/Permutation Matrices | ||
| 21.3 Functions That Are Aware of These Matrices | ||
| 21.4 Examples of Usage | ||
| 21.5 Differences in Treatment of Zero Elements |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A diagonal matrix is defined as a matrix that has zero entries outside the main
diagonal; that is,
D(i,j) == 0 if i != j.
Most often, square diagonal matrices are considered; however, the definition can
equally be applied to non-square matrices, in which case we usually speak of a
rectangular diagonal matrix.
A permutation matrix is defined as a square matrix that has a single element
equal to unity in each row and each column; all other elements are zero. That
is, there exists a permutation (vector)
p such that P(i,j) == 1 if j == p(i) and
P(i,j) == 0 otherwise.
Octave provides special treatment of real and complex rectangular diagonal matrices, as well as permutation matrices. They are stored as special objects, using efficient storage and algorithms, facilitating writing both readable and efficient matrix algebra expressions in the Octave language.
| 21.1.1 Creating Diagonal Matrices | ||
| 21.1.2 Creating Permutation Matrices | ||
| 21.1.3 Explicit and Implicit Conversions |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The most common and easiest way to create a diagonal matrix is using the
built-in function diag. The expression diag (v), with v a
vector, will create a square diagonal matrix with elements on the main diagonal
given by the elements of v, and size equal to the length of v.
diag (v, m, n) can be used to construct a rectangular diagonal matrix.
The result of these expressions will be a special diagonal matrix object, rather
than a general matrix object.
Diagonal matrix with unit elements can be created using eye. Some other built-in functions can also return diagonal matrices. Examples include balance or inv.
Example:
diag (1:4) ⇒ Diagonal Matrix 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 diag (1:3,5,3) ⇒ Diagonal Matrix 1 0 0 0 2 0 0 0 3 0 0 0 0 0 0 |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
For creating permutation matrices, Octave does not introduce a new function, but rather overrides an existing syntax: permutation matrices can be conveniently created by indexing an identity matrix by permutation vectors. That is, if q is a permutation vector of length n, the expression
P = eye (n) (:, q); |
will create a permutation matrix - a special matrix object.
eye (n) (q, :) |
will also work (and create a row permutation matrix), as well as
eye (n) (q1, q2). |
For example:
eye (4) ([1,3,2,4],:) ⇒ Permutation Matrix 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 eye (4) (:,[1,3,2,4]) ⇒ Permutation Matrix 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 |
Mathematically, an identity matrix is both diagonal and permutation matrix.
In Octave, eye (n) returns a diagonal matrix, because a matrix
can only have one class. You can convert this diagonal matrix to a permutation
matrix by indexing it by an identity permutation, as shown below.
This is a special property of the identity matrix; indexing other diagonal
matrices generally produces a full matrix.
eye (3) ⇒ Diagonal Matrix 1 0 0 0 1 0 0 0 1 eye(3)(1:3,:) ⇒ Permutation Matrix 1 0 0 0 1 0 0 0 1 |
Some other built-in functions can also return permutation matrices. Examples include inv or lu.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The diagonal and permutation matrices are special objects in their own right. A number of operations and built-in functions are defined for these matrices to use special, more efficient code than would be used for a full matrix in the same place. Examples are given in further sections.
To facilitate smooth mixing with full matrices, backward compatibility, and compatibility with MATLAB, the diagonal and permutation matrices should allow any operation that works on full matrices, and will either treat it specially, or implicitly convert themselves to full matrices.
Instances include matrix indexing, except for extracting a single element or a leading submatrix, indexed assignment, or applying most mapper functions, such as exp.
An explicit conversion to a full matrix can be requested using the built-in function full. It should also be noted that the diagonal and permutation matrix objects will cache the result of the conversion after it is first requested (explicitly or implicitly), so that subsequent conversions will be very cheap.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
As has been already said, diagonal and permutation matrices make it possible to use efficient algorithms while preserving natural linear algebra syntax. This section describes in detail the operations that are treated specially when performed on these special matrix objects.
| 21.2.1 Expressions Involving Diagonal Matrices | ||
| 21.2.2 Expressions Involving Permutation Matrices |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Assume D is a diagonal matrix. If M is a full matrix,
then D*M will scale the rows of M. That means,
if S = D*M, then for each pair of indices
i,j it holds
S(i,j) = D(i,i) * M(i,j). |
Similarly, M*D will do a column scaling.
The matrix D may also be rectangular, m-by-n where m != n.
If m < n, then the expression D*M is equivalent to
D(:,1:m) * M(1:m,:), |
i.e., trailing n-m rows of M are ignored. If m > n,
then D*M is equivalent to
[D(1:n,n) * M; zeros(m-n, columns (M))], |
i.e., null rows are appended to the result.
The situation for right-multiplication M*D is analogous.
The expressions D \ M and M / D perform inverse scaling.
They are equivalent to solving a diagonal (or rectangular diagonal)
in a least-squares minimum-norm sense. In exact arithmetic, this is
equivalent to multiplying by a pseudoinverse. The pseudoinverse of
a rectangular diagonal matrix is again a rectangular diagonal matrix
with swapped dimensions, where each nonzero diagonal element is replaced
by its reciprocal.
The matrix division algorithms do, in fact, use division rather than
multiplication by reciprocals for better numerical accuracy; otherwise, they
honor the above definition. Note that a diagonal matrix is never truncated due
to ill-conditioning; otherwise, it would not be of much use for scaling. This
is typically consistent with linear algebra needs. A full matrix that only
happens to be diagonal (and is thus not a special object) is of course treated
normally.
Multiplication and division by diagonal matrices work efficiently also when
combined with sparse matrices, i.e., D*S, where D is a diagonal
matrix and S is a sparse matrix scales the rows of the sparse matrix and
returns a sparse matrix. The expressions S*D, D\S, S/D
work analogically.
If D1 and D2 are both diagonal matrices, then the expressions
D1 + D2 D1 - D2 D1 * D2 D1 / D2 D1 \ D2 |
again produce diagonal matrices, provided that normal dimension matching rules are obeyed. The relations used are same as described above.
Also, a diagonal matrix D can be multiplied or divided by a scalar, or raised to a scalar power if it is square, producing diagonal matrix result in all cases.
A diagonal matrix can also be transposed or conjugate-transposed, giving the
expected result. Extracting a leading submatrix of a diagonal matrix, i.e.,
D(1:m,1:n), will produce a diagonal matrix, other indexing expressions
will implicitly convert to full matrix.
Adding a diagonal matrix to a full matrix only operates on the diagonal elements. Thus,
A = A + eps * eye (n) |
is an efficient method of augmenting the diagonal of a matrix. Subtraction works analogically.
When involved in expressions with other element-by-element operators, .*,
./, .\ or .^, an implicit conversion to full matrix will
take place. This is not always strictly necessary but chosen to facilitate
better consistency with MATLAB.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
If P is a permutation matrix and M a matrix, the expression
P*M will permute the rows of M. Similarly, M*P will
yield a column permutation.
Matrix division P\M and M/P can be used to do inverse permutation.
The previously described syntax for creating permutation matrices can actually
help an user to understand the connection between a permutation matrix and
a permuting vector. Namely, the following holds, where I = eye (n)
is an identity matrix:
I(p,:) * M = (I*M) (p,:) = M(p,:) |
Similarly,
M * I(:,p) = (M*I) (:,p) = M(:,p) |
The expressions I(p,:) and I(:,p) are permutation matrices.
A permutation matrix can be transposed (or conjugate-transposed, which is the
same, because a permutation matrix is never complex), inverting the
permutation, or equivalently, turning a row-permutation matrix into a
column-permutation one. For permutation matrices, transpose is equivalent to
inversion, thus P\M is equivalent to P'*M. Transpose of a
permutation matrix (or inverse) is a constant-time operation, flipping only a
flag internally, and thus the choice between the two above equivalent
expressions for inverse permuting is completely up to the user’s taste.
Multiplication and division by permutation matrices works efficiently also when
combined with sparse matrices, i.e., P*S, where P is a permutation
matrix and S is a sparse matrix permutes the rows of the sparse matrix and
returns a sparse matrix. The expressions S*P, P\S, S/P
work analogically.
Two permutation matrices can be multiplied or divided (if their sizes match), performing a composition of permutations. Also a permutation matrix can be indexed by a permutation vector (or two vectors), giving again a permutation matrix. Any other operations do not generally yield a permutation matrix and will thus trigger the implicit conversion.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section lists the built-in functions that are aware of diagonal and permutation matrices on input, or can return them as output. Passed to other functions, these matrices will in general trigger an implicit conversion. (Of course, user-defined dynamically linked functions may also work with diagonal or permutation matrices).
| 21.3.1 Diagonal Matrix Functions | ||
| 21.3.2 Permutation Matrix Functions |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
inv and pinv can be applied to a diagonal matrix, yielding again a diagonal matrix. det will use an efficient straightforward calculation when given a diagonal matrix, as well as cond. The following mapper functions can be applied to a diagonal matrix without converting it to a full one: abs, real, imag, conj, sqrt. A diagonal matrix can also be returned from the balance and svd functions. The sparse function will convert a diagonal matrix efficiently to a sparse matrix.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
inv and pinv will invert a permutation matrix, preserving its specialness. det can be applied to a permutation matrix, efficiently calculating the sign of the permutation (which is equal to the determinant).
A permutation matrix can also be returned from the built-in functions lu and qr, if a pivoted factorization is requested.
The sparse function will convert a permutation matrix efficiently to a sparse matrix. The find function will also work efficiently with a permutation matrix, making it possible to conveniently obtain the permutation indices.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following can be used to solve a linear system A*x = b
using the pivoted LU factorization:
[L, U, P] = lu (A); ## now L*U = P*A x = U \ L \ P*b; |
This is one way to normalize columns of a matrix X to unit norm:
s = norm (X, "columns"); X /= diag (s); |
The same can also be accomplished with broadcasting (see section Broadcasting):
s = norm (X, "columns"); X ./= s; |
The following expression is a way to efficiently calculate the sign of a permutation, given by a permutation vector p. It will also work in earlier versions of Octave, but slowly.
det (eye (length (p))(p, :)) |
Finally, here’s how to solve a linear system A*x = b
with Tikhonov regularization (ridge regression) using SVD (a skeleton only):
m = rows (A); n = columns (A); [U, S, V] = svd (A); ## determine the regularization factor alpha ## alpha = … ## transform to orthogonal basis b = U'*b; ## Use the standard formula, replacing A with S. ## S is diagonal, so the following will be very fast and accurate. x = (S'*S + alpha^2 * eye (n)) \ (S' * b); ## transform to solution basis x = V*x; |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Making diagonal and permutation matrices special matrix objects in their own right and the consequent usage of smarter algorithms for certain operations implies, as a side effect, small differences in treating zeros. The contents of this section apply also to sparse matrices, discussed in the following chapter. (see section Sparse Matrices)
The IEEE floating point standard defines the result of the expressions 0*Inf and
0*NaN as NaN. This is widely agreed to be a good
compromise.
Numerical software dealing with structured and sparse matrices (including
Octave) however, almost always makes a distinction between a "numerical zero"
and an "assumed zero".
A "numerical zero" is a zero value occurring in a place where any floating-point
value could occur. It is normally stored somewhere in memory as an explicit
value.
An "assumed zero", on the contrary, is a zero matrix element implied by the
matrix structure (diagonal, triangular) or a sparsity pattern; its value is
usually not stored explicitly anywhere, but is implied by the underlying
data structure.
The primary distinction is that an assumed zero, when multiplied
by any number, or divided by any nonzero number,
yields *always* a zero, even when, e.g., multiplied by Inf
or divided by NaN.
The reason for this behavior is that the numerical multiplication is not
actually performed anywhere by the underlying algorithm; the result is
just assumed to be zero. Equivalently, one can say that the part of the
computation involving assumed zeros is performed symbolically, not numerically.
This behavior not only facilitates the most straightforward and efficient implementation of algorithms, but also preserves certain useful invariants, like:
all of these natural mathematical truths would be invalidated by treating assumed zeros as numerical ones.
Note that MATLAB does not strictly follow this principle and converts assumed zeros to numerical zeros in certain cases, while not doing so in other cases. As of today, there are no intentions to mimic such behavior in Octave.
Examples of effects of assumed zeros vs. numerical zeros:
Inf * eye (3)
⇒
Inf 0 0
0 Inf 0
0 0 Inf
Inf * speye (3)
⇒
Compressed Column Sparse (rows = 3, cols = 3, nnz = 3 [33%])
(1, 1) -> Inf
(2, 2) -> Inf
(3, 3) -> Inf
Inf * full (eye (3))
⇒
Inf NaN NaN
NaN Inf NaN
NaN NaN Inf
|
diag (1:3) * [NaN; 1; 1]
⇒
NaN
2
3
sparse (1:3,1:3,1:3) * [NaN; 1; 1]
⇒
NaN
2
3
[1,0,0;0,2,0;0,0,3] * [NaN; 1; 1]
⇒
NaN
NaN
NaN
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 22.1 Creation and Manipulation of Sparse Matrices | ||
| 22.2 Linear Algebra on Sparse Matrices | ||
| 22.3 Iterative Techniques Applied to Sparse Matrices | Iterative Techniques | |
| 22.4 Real Life Example using Sparse Matrices | Using Sparse Matrices |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The size of mathematical problems that can be treated at any particular time is generally limited by the available computing resources. Both, the speed of the computer and its available memory place limitation on the problem size.
There are many classes of mathematical problems which give rise to matrices, where a large number of the elements are zero. In this case it makes sense to have a special matrix type to handle this class of problems where only the non-zero elements of the matrix are stored. Not only does this reduce the amount of memory to store the matrix, but it also means that operations on this type of matrix can take advantage of the a priori knowledge of the positions of the non-zero elements to accelerate their calculations.
A matrix type that stores only the non-zero elements is generally called sparse. It is the purpose of this document to discuss the basics of the storage and creation of sparse matrices and the fundamental operations on them.
| 22.1.1 Storage of Sparse Matrices | ||
| 22.1.2 Creating Sparse Matrices | ||
| 22.1.3 Finding Information about Sparse Matrices | ||
| 22.1.4 Basic Operators and Functions on Sparse Matrices |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
It is not strictly speaking necessary for the user to understand how sparse matrices are stored. However, such an understanding will help to get an understanding of the size of sparse matrices. Understanding the storage technique is also necessary for those users wishing to create their own oct-files.
There are many different means of storing sparse matrix data. What all of the methods have in common is that they attempt to reduce the complexity and storage given a priori knowledge of the particular class of problems that will be solved. A good summary of the available techniques for storing sparse matrix is given by Saad (8). With full matrices, knowledge of the point of an element of the matrix within the matrix is implied by its position in the computers memory. However, this is not the case for sparse matrices, and so the positions of the non-zero elements of the matrix must equally be stored.
An obvious way to do this is by storing the elements of the matrix as triplets, with two elements being their position in the array (rows and column) and the third being the data itself. This is conceptually easy to grasp, but requires more storage than is strictly needed.
The storage technique used within Octave is the compressed column format. It is similar to the Yale format. (9) In this format the position of each element in a row and the data are stored as previously. However, if we assume that all elements in the same column are stored adjacent in the computers memory, then we only need to store information on the number of non-zero elements in each column, rather than their positions. Thus assuming that the matrix has more non-zero elements than there are columns in the matrix, we win in terms of the amount of memory used.
In fact, the column index contains one more element than the number of columns, with the first element always being zero. The advantage of this is a simplification in the code, in that there is no special case for the first or last columns. A short example, demonstrating this in C is.
for (j = 0; j < nc; j++)
for (i = cidx(j); i < cidx(j+1); i++)
printf ("non-zero element (%i,%i) is %d\n",
ridx(i), j, data(i));
|
A clear understanding might be had by considering an example of how the above applies to an example matrix. Consider the matrix
1 2 0 0
0 0 0 3
0 0 0 4
|
The non-zero elements of this matrix are
(1, 1) ⇒ 1 (1, 2) ⇒ 2 (2, 4) ⇒ 3 (3, 4) ⇒ 4 |
This will be stored as three vectors cidx, ridx and data, representing the column indexing, row indexing and data respectively. The contents of these three vectors for the above matrix will be
cidx = [0, 1, 2, 2, 4] ridx = [0, 0, 1, 2] data = [1, 2, 3, 4] |
Note that this is the representation of these elements with the first row
and column assumed to start at zero, while in Octave itself the row and
column indexing starts at one. Thus the number of elements in the
i-th column is given by cidx (i + 1) -
cidx (i).
Although Octave uses a compressed column format, it should be noted that compressed row formats are equally possible. However, in the context of mixed operations between mixed sparse and dense matrices, it makes sense that the elements of the sparse matrices are in the same order as the dense matrices. Octave stores dense matrices in column major ordering, and so sparse matrices are equally stored in this manner.
A further constraint on the sparse matrix storage used by Octave is that all elements in the rows are stored in increasing order of their row index, which makes certain operations faster. However, it imposes the need to sort the elements on the creation of sparse matrices. Having disordered elements is potentially an advantage in that it makes operations such as concatenating two sparse matrices together easier and faster, however it adds complexity and speed problems elsewhere.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There are several means to create sparse matrix.
There are many functions that directly return sparse matrices. These include speye, sprand, diag, etc.
The function sparse allows a sparse matrix to be constructed from three vectors representing the row, column and data. Alternatively, the function spconvert uses a three column matrix format to allow easy importation of data from elsewhere.
The function sparse or spalloc can be used to create an empty matrix that is then filled by the user
The user can directly create the sparse matrix within an oct-file.
There are several basic functions to return specific sparse
matrices. For example the sparse identity matrix, is a matrix that is
often needed. It therefore has its own function to create it as
speye (n) or speye (r, c), which
creates an n-by-n or r-by-c sparse identity
matrix.
Another typical sparse matrix that is often needed is a random distribution
of random elements. The functions sprand and sprandn perform
this for uniform and normal random distributions of elements. They have exactly
the same calling convention, where sprand (r, c, d),
creates an r-by-c sparse matrix with a density of filled
elements of d.
Other functions of interest that directly create sparse matrices, are diag or its generalization spdiags, that can take the definition of the diagonals of the matrix and create the sparse matrix that corresponds to this. For example,
s = diag (sparse (randn (1,n)), -1); |
creates a sparse (n+1)-by-(n+1) sparse matrix with a single diagonal defined.
A generalization of the function diag. Called with a single
input argument, the non-zero diagonals c of A are extracted.
With two arguments the diagonals to extract are given by the vector
c.
The other two forms of spdiags modify the input matrix by
replacing the diagonals. They use the columns of v to replace
the columns represented by the vector c. If the sparse matrix
A is defined then the diagonals of this matrix are replaced.
Otherwise a matrix of m by n is created with the
diagonals given by v.
Negative values of c represent diagonals below the main diagonal, and positive values of c diagonals above the main diagonal.
For example:
spdiags (reshape (1:12, 4, 3), [-1 0 1], 5, 4)
⇒ 5 10 0 0
1 6 11 0
0 2 7 12
0 0 3 8
0 0 0 4
|
Return a sparse identity matrix of size mxn.
The implementation is significantly more efficient than
sparse (eye (m)) as the full matrix is not constructed.
Called with a single argument a square matrix of size m-by-m is created. If called with a single vector argument sz, this argument is taken to be the size of the matrix to create.
Replace the non-zero entries of S with ones. This creates a sparse matrix with the same structure as S.
Generate a random sparse matrix. The size of the matrix will be mxn, with a density of values given by d. d must be between 0 and 1 inclusive. Values will be uniformly distributed between 0 and 1.
If called with a single matrix argument, a random sparse matrix is generated wherever the matrix S is non-zero.
Generate a random sparse matrix. The size of the matrix will be mxn, with a density of values given by d. d must be between 0 and 1 inclusive. Values will be normally distributed with a mean of zero and a variance of 1.
If called with a single matrix argument, a random sparse matrix is generated wherever the matrix S is non-zero.
Generate a symmetric random sparse matrix.
The size of the matrix will be nxn, with a density of values given by d. d must be between 0 and 1 inclusive. Values will be normally distributed with a mean of zero and a variance of 1.
If called with a single matrix argument, a random sparse matrix is generated wherever the matrix S is non-zero in its lower triangular part.
The recommended way for the user to create a sparse matrix, is to create two vectors containing the row and column index of the data and a third vector of the same size containing the data to be stored. For example,
ri = ci = d = [];
for j = 1:c
ri = [ri; randperm(r,n)'];
ci = [ci; j*ones(n,1)];
d = [d; rand(n,1)];
endfor
s = sparse (ri, ci, d, r, c);
|
creates an r-by-c sparse matrix with a random distribution of n (<r) elements per column. The elements of the vectors do not need to be sorted in any particular order as Octave will sort them prior to storing the data. However, pre-sorting the data will make the creation of the sparse matrix faster.
The function spconvert takes a three or four column real matrix. The first two columns represent the row and column index respectively and the third and four columns, the real and imaginary parts of the sparse matrix. The matrix can contain zero elements and the elements can be sorted in any order. Adding zero elements is a convenient way to define the size of the sparse matrix. For example:
s = spconvert ([1 2 3 4; 1 3 4 4; 1 2 3 0]')
⇒ Compressed Column Sparse (rows=4, cols=4, nnz=3)
(1 , 1) -> 1
(2 , 3) -> 2
(3 , 4) -> 3
|
An example of creating and filling a matrix might be
k = 5;
nz = r * k;
s = spalloc (r, c, nz)
for j = 1:c
idx = randperm (r);
s (:, j) = [zeros(r - k, 1); ...
rand(k, 1)] (idx);
endfor
|
It should be noted, that due to the way that the Octave assignment functions are written that the assignment will reallocate the memory used by the sparse matrix at each iteration of the above loop. Therefore the spalloc function ignores the nz argument and does not pre-assign the memory for the matrix. Therefore, it is vitally important that code using to above structure should be vectorized as much as possible to minimize the number of assignments and reduce the number of memory allocations.
Return a full storage matrix from a sparse, diagonal, permutation matrix, or a range.
Create an m-by-n sparse matrix with pre-allocated space for at most nz nonzero elements.
This is useful for building a matrix incrementally by a sequence of indexed
assignments. Subsequent indexed assignments after spalloc will reuse
the pre-allocated memory, provided they are of one of the simple forms
s(I:J) = x
s(:,I:J) = x
s(K:L,I:J) = x
and that the following conditions are met:
Partial movement of data may still occur, but in general the assignment will be more memory and time efficient under these circumstances. In particular, it is possible to efficiently build a pre-allocated sparse matrix from a contiguous block of columns.
The amount of pre-allocated memory for a given matrix may be queried using
the function nzmax.
Create a sparse matrix from a full matrix or row, column, value triplets.
If a is a full matrix, convert it to a sparse matrix representation, removing all zero values in the process.
Given the integer index vectors i and j, and a 1-by-nnz
vector of real or complex values sv, construct the sparse matrix
S(i(k),j(k)) = sv(k) with overall
dimensions m and n. If any of sv, i or j are
scalars, they are expanded to have a common size.
If m or n are not specified their values are derived from the
maximum index in the vectors i and j as given by
m = max (i), n = max (j).
Note: if multiple values are specified with the same i,
j indices, the corresponding value in s will be the sum of the
values at the repeated location. See accumarray for an example of how
to produce different behavior, such as taking the minimum instead.
If the option "unique" is given, and more than one value is
specified at the same i, j indices, then the last specified
value will be used.
sparse (m, n) will create an empty mxn sparse
matrix and is equivalent to sparse ([], [], [], m, n)
The argument nzmax is ignored but accepted for compatibility with
MATLAB.
Example 1 (sum at repeated indices):
i = [1 1 2]; j = [1 1 2]; sv = [3 4 5]; sparse (i, j, sv, 3, 4) ⇒ Compressed Column Sparse (rows = 3, cols = 4, nnz = 2 [17%]) (1, 1) -> 7 (2, 2) -> 5 |
Example 2 ("unique" option):
i = [1 1 2]; j = [1 1 2]; sv = [3 4 5]; sparse (i, j, sv, 3, 4, "unique") ⇒ Compressed Column Sparse (rows = 3, cols = 4, nnz = 2 [17%]) (1, 1) -> 4 (2, 2) -> 5 |
See also: full, accumarray, spalloc, spdiags, speye, spones, sprand, sprandn, sprandsym, spconvert, spfun.
Convert a simple sparse matrix format easily generated by other programs into Octave’s internal sparse format.
The input m is either a 3 or 4 column real matrix, containing the row, column, real, and imaginary parts of the elements of the sparse matrix. An element with a zero real and imaginary part can be used to force a particular matrix size.
See also: sparse.
The above problem of memory reallocation can be avoided in oct-files. However, the construction of a sparse matrix from an oct-file is more complex than can be discussed here. See section External Code Interface, for a full description of the techniques involved.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There are a number of functions that allow information concerning sparse matrices to be obtained. The most basic of these is issparse that identifies whether a particular Octave object is in fact a sparse matrix.
Another very basic function is nnz that returns the number of non-zero entries there are in a sparse matrix, while the function nzmax returns the amount of storage allocated to the sparse matrix. Note that Octave tends to crop unused memory at the first opportunity for sparse objects. There are some cases of user created sparse objects where the value returned by nzmax will not be the same as nnz, but in general they will give the same result. The function spstats returns some basic statistics on the columns of a sparse matrix including the number of elements, the mean and the variance of each column.
Return true if x is a sparse matrix.
See also: ismatrix.
Return the number of non-zero elements in a.
Return a vector of the non-zero values of the sparse matrix s.
Return the amount of storage allocated to the sparse matrix SM.
Note that Octave tends to crop unused memory at the first opportunity
for sparse objects. Thus, in general the value of nzmax will be the
the same as nnz except for some cases of user-created sparse objects.
Return the stats for the non-zero elements of the sparse matrix S. count is the number of non-zeros in each column, mean is the mean of the non-zeros in each column, and var is the variance of the non-zeros in each column.
Called with two input arguments, if S is the data and j
is the bin number for the data, compute the stats for each bin. In
this case, bins can contain data values of zero, whereas with
spstats (S) the zeros may disappear.
When solving linear equations involving sparse matrices Octave determines the means to solve the equation based on the type of the matrix (see section Linear Algebra on Sparse Matrices). Octave probes the matrix type when the div (/) or ldiv (\) operator is first used with the matrix and then caches the type. However the matrix_type function can be used to determine the type of the sparse matrix prior to use of the div or ldiv operators. For example,
a = tril (sprandn (1024, 1024, 0.02), -1) ...
+ speye (1024);
matrix_type (a);
ans = Lower
|
shows that Octave correctly determines the matrix type for lower triangular matrices. matrix_type can also be used to force the type of a matrix to be a particular type. For example:
a = matrix_type (tril (sprandn (1024, ... 1024, 0.02), -1) + speye (1024), "Lower"); |
This allows the cost of determining the matrix type to be avoided. However, incorrectly defining the matrix type will result in incorrect results from solutions of linear equations, and so it is entirely the responsibility of the user to correctly identify the matrix type
There are several graphical means of finding out information about sparse matrices. The first is the spy command, which displays the structure of the non-zero elements of the matrix. See fig:spmatrix, for an example of the use of spy. More advanced graphical information can be obtained with the treeplot, etreeplot and gplot commands.
Figure 22.1: Structure of simple sparse matrix.
One use of sparse matrices is in graph theory, where the interconnections between nodes are represented as an adjacency matrix. That is, if the i-th node in a graph is connected to the j-th node. Then the ij-th node (and in the case of undirected graphs the ji-th node) of the sparse adjacency matrix is non-zero. If each node is then associated with a set of coordinates, then the gplot command can be used to graphically display the interconnections between nodes.
As a trivial example of the use of gplot consider the example,
A = sparse ([2,6,1,3,2,4,3,5,4,6,1,5],
[1,1,2,2,3,3,4,4,5,5,6,6],1,6,6);
xy = [0,4,8,6,4,2;5,0,5,7,5,7]';
gplot (A,xy)
|
which creates an adjacency matrix A where node 1 is connected
to nodes 2 and 6, node 2 with nodes 1 and 3, etc. The coordinates of
the nodes are given in the n-by-2 matrix xy.
See fig:gplot.
Figure 22.2: Simple use of the gplot command.
The dependencies between the nodes of a Cholesky factorization can be
calculated in linear time without explicitly needing to calculate the
Cholesky factorization by the etree command. This command
returns the elimination tree of the matrix and can be displayed
graphically by the command treeplot (etree (A)) if A is
symmetric or treeplot (etree (A+A')) otherwise.
Plot the sparsity pattern of the sparse matrix x.
If the argument markersize is given as a scalar value, it is used to
determine the point size in the plot. If the string line_spec is
given it is passed to plot and determines the appearance of the plot.
Return the elimination tree for the matrix S. By default S
is assumed to be symmetric and the symmetric elimination tree is
returned. The argument typ controls whether a symmetric or
column elimination tree is returned. Valid values of typ are
"sym" or "col", for symmetric or column elimination tree
respectively.
Called with a second argument, etree also returns the postorder
permutations on the tree.
Plot the elimination tree of the matrix A or
A+A' if A in not symmetric. The optional
parameters node_style and edge_style define the output
style.
Plot a graph defined by A and xy in the graph theory sense. A is the adjacency matrix of the array to be plotted and xy is an n-by-2 matrix containing the coordinates of the nodes of the graph.
The optional parameter line_style defines the output style for the plot. Called with no output arguments the graph is plotted directly. Otherwise, return the coordinates of the plot in x and y.
Produce a graph of tree or forest. The first argument is vector of predecessors, optional parameters node_style and edge_style define the output style. The complexity of the algorithm is O(n) in terms of is time and memory requirements.
treelayout lays out a tree or a forest. The first argument tree is a vector of predecessors, optional parameter permutation is an optional postorder permutation. The complexity of the algorithm is O(n) in terms of time and memory requirements.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 22.1.4.1 Sparse Functions | ||
| 22.1.4.2 Return Types of Operators and Functions | ||
| 22.1.4.3 Mathematical Considerations |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Many Octave functions have been overloaded to work with either sparse or full matrices. There is no difference in calling convention when using an overloaded function with a sparse matrix, however, there is also no access to potentially sparse-specific features. At any time the sparse matrix specific version of a function can be used by explicitly calling its function name.
The table below lists all of the sparse functions of Octave. Note that the names of the specific sparse forms of the functions are typically the same as the general versions with a sp prefix. In the table below, and in the rest of this article, the specific sparse versions of functions are used.
spalloc, spdiags, speye, sprand, sprandn, sprandsym
full, sparse, spconvert
issparse, nnz, nonzeros, nzmax, spfun, spones, spy
etree, etreeplot, gplot, treeplot
amd, ccolamd, colamd, colperm, csymamd, dmperm, symamd, randperm, symrcm
condest, eigs, matrix_type, normest, sprank, spaugment, svds
luinc, pcg, pcr
spparms, symbfact, spstats
In addition all of the standard Octave mapper functions (i.e., basic math functions that take a single argument) such as abs, etc. can accept sparse matrices. The reader is referred to the documentation supplied with these functions within Octave itself for further details.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The two basic reasons to use sparse matrices are to reduce the memory usage and to not have to do calculations on zero elements. The two are closely related in that the computation time on a sparse matrix operator or function is roughly linear with the number of non-zero elements.
Therefore, there is a certain density of non-zero elements of a matrix where it no longer makes sense to store it as a sparse matrix, but rather as a full matrix. For this reason operators and functions that have a high probability of returning a full matrix will always return one. For example adding a scalar constant to a sparse matrix will almost always make it a full matrix, and so the example,
speye (3) + 0 ⇒ 1 0 0 0 1 0 0 0 1 |
returns a full matrix as can be seen.
Additionally, if sparse_auto_mutate is true, all sparse functions
test the amount of memory occupied by the sparse matrix to see if the
amount of storage used is larger than the amount used by the full
equivalent. Therefore speye (2) * 1 will return a full matrix as
the memory used is smaller for the full version than the sparse version.
As all of the mixed operators and functions between full and sparse
matrices exist, in general this does not cause any problems. However,
one area where it does cause a problem is where a sparse matrix is
promoted to a full matrix, where subsequent operations would resparsify
the matrix. Such cases are rare, but can be artificially created, for
example (fliplr (speye (3)) + speye (3)) - speye (3) gives a full
matrix when it should give a sparse one. In general, where such cases
occur, they impose only a small memory penalty.
There is however one known case where this behavior of Octave’s sparse matrices will cause a problem. That is in the handling of the diag function. Whether diag returns a sparse or full matrix depending on the type of its input arguments. So
a = diag (sparse ([1,2,3]), -1); |
should return a sparse matrix. To ensure this actually happens, the sparse function, and other functions based on it like speye, always returns a sparse matrix, even if the memory used will be larger than its full representation.
Query or set the internal variable that controls whether Octave will automatically mutate sparse matrices to full matrices to save memory. For example:
s = speye (3); sparse_auto_mutate (false); s(:, 1) = 1; typeinfo (s) ⇒ sparse matrix sparse_auto_mutate (true); s(1, :) = 1; typeinfo (s) ⇒ matrix |
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
Note that the sparse_auto_mutate option is incompatible with
MATLAB, and so it is off by default.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The attempt has been made to make sparse matrices behave in exactly the same manner as there full counterparts. However, there are certain differences and especially differences with other products sparse implementations.
First, the "./" and ".^" operators must be used with care.
Consider what the examples
s = speye (4); a1 = s .^ 2; a2 = s .^ s; a3 = s .^ -2; a4 = s ./ 2; a5 = 2 ./ s; a6 = s ./ s; |
will give. The first example of s raised to the power of 2 causes
no problems. However s raised element-wise to itself involves a
large number of terms 0 .^ 0 which is 1. There s .^
s is a full matrix.
Likewise s .^ -2 involves terms like 0 .^ -2 which
is infinity, and so s .^ -2 is equally a full matrix.
For the "./" operator s ./ 2 has no problems, but
2 ./ s involves a large number of infinity terms as well
and is equally a full matrix. The case of s ./ s
involves terms like 0 ./ 0 which is a NaN and so this
is equally a full matrix with the zero elements of s filled with
NaN values.
The above behavior is consistent with full matrices, but is not consistent with sparse implementations in other products.
A particular problem of sparse matrices comes about due to the fact that as the zeros are not stored, the sign-bit of these zeros is equally not stored. In certain cases the sign-bit of zero is important. For example:
a = 0 ./ [-1, 1; 1, -1];
b = 1 ./ a
⇒ -Inf Inf
Inf -Inf
c = 1 ./ sparse (a)
⇒ Inf Inf
Inf Inf
|
To correct this behavior would mean that zero elements with a negative sign-bit would need to be stored in the matrix to ensure that their sign-bit was respected. This is not done at this time, for reasons of efficiency, and so the user is warned that calculations where the sign-bit of zero is important must not be done using sparse matrices.
In general any function or operator used on a sparse matrix will
result in a sparse matrix with the same or a larger number of non-zero
elements than the original matrix. This is particularly true for the
important case of sparse matrix factorizations. The usual way to
address this is to reorder the matrix, such that its factorization is
sparser than the factorization of the original matrix. That is the
factorization of L * U = P * S * Q has sparser terms L
and U than the equivalent factorization L * U = S.
Several functions are available to reorder depending on the type of the matrix to be factorized. If the matrix is symmetric positive-definite, then symamd or csymamd should be used. Otherwise amd, colamd or ccolamd should be used. For completeness the reordering functions colperm and randperm are also available.
See fig:simplematrix, for an example of the structure of a simple positive definite matrix.
Figure 22.3: Structure of simple sparse matrix.
The standard Cholesky factorization of this matrix can be
obtained by the same command that would be used for a full
matrix. This can be visualized with the command
r = chol (A); spy (r);.
See fig:simplechol.
The original matrix had
598
non-zero terms, while this Cholesky factorization has
10200,
with only half of the symmetric matrix being stored. This
is a significant level of fill in, and although not an issue
for such a small test case, can represents a large overhead
in working with other sparse matrices.
The appropriate sparsity preserving permutation of the original
matrix is given by symamd and the factorization using this
reordering can be visualized using the command q = symamd (A);
r = chol (A(q,q)); spy (r). This gives
399
non-zero terms which is a significant improvement.
The Cholesky factorization itself can be used to determine the
appropriate sparsity preserving reordering of the matrix during the
factorization, In that case this might be obtained with three return
arguments as [r, p, q] = chol (A); spy (r).
Figure 22.4: Structure of the unpermuted Cholesky factorization of the above matrix.
Figure 22.5: Structure of the permuted Cholesky factorization of the above matrix.
In the case of an asymmetric matrix, the appropriate sparsity
preserving permutation is colamd and the factorization using
this reordering can be visualized using the command
q = colamd (A); [l, u, p] = lu (A(:,q)); spy (l+u).
Finally, Octave implicitly reorders the matrix when using the div (/) and ldiv (\) operators, and so no the user does not need to explicitly reorder the matrix to maximize performance.
Return the approximate minimum degree permutation of a matrix. This
permutation such that the Cholesky factorization of S
(p, p) tends to be sparser than the Cholesky factorization
of S itself. amd is typically faster than symamd but
serves a similar purpose.
The optional parameter opts is a structure that controls the
behavior of amd. The fields of the structure are
Determines what amd considers to be a dense row or column of the
input matrix. Rows or columns with more than max(16, (dense *
sqrt (n) entries, where n is the order of the matrix S,
are ignored by amd during the calculation of the permutation
The value of dense must be a positive scalar and its default value is 10.0
If this value is a nonzero scalar, then amd performs aggressive
absorption. The default is not to perform aggressive absorption.
The author of the code itself is Timothy A. Davis davis@cise.ufl.edu, University of Florida (see http://www.cise.ufl.edu/research/sparse/amd).
Constrained column approximate minimum degree permutation.
p = ccolamd (S) returns the column approximate minimum
degree permutation vector for the sparse matrix S. For a non-symmetric
matrix
S,
S(:, p) tends to have sparser LU factors than
S. chol (S(:, p)' * S(:, p)) also
tends to be sparser than chol (S' * S). p =
ccolamd (S, 1) optimizes the ordering for lu (S(:,
p)). The ordering is followed by a column elimination tree
post-ordering.
knobs is an optional 1-element to 5-element input vector, with a
default value of [0 10 10 1 0] if not present or empty. Entries not
present are set to their defaults.
knobs(1)if nonzero, the ordering is optimized for lu (S(:, p)). It will be a
poor ordering for chol (S(:, p)' * S(:,
p)). This is the most important knob for ccolamd.
knobs(2)if S is m-by-n, rows with more than max (16, knobs(2) *
sqrt (n)) entries are ignored.
knobs(3)columns with more than max (16, knobs(3) * sqrt (min (m,
n))) entries are ignored and ordered last in the output permutation
(subject to the cmember constraints).
knobs(4)if nonzero, aggressive absorption is performed.
knobs(5)if nonzero, statistics and knobs are printed.
cmember is an optional vector of length n. It defines the
constraints on the column ordering. If cmember(j) = c,
then column j is in constraint set c (c must be in the
range 1 to
n). In the output permutation p, all columns in set 1 appear
first, followed by all columns in set 2, and so on. cmember =
ones (1,n) if not present or empty.
ccolamd (S, [], 1 : n) returns 1 : n
p = ccolamd (S) is about the same as
p = colamd (S). knobs and its default values
differ. colamd always does aggressive absorption, and it finds an
ordering suitable for both lu (S(:, p)) and chol
(S(:, p)' * S(:, p)); it cannot optimize its
ordering for lu (S(:, p)) to the extent that
ccolamd (S, 1) can.
stats is an optional 20-element output vector that provides data
about the ordering and the validity of the input matrix S. Ordering
statistics are in stats(1 : 3). stats(1) and
stats(2) are the number of dense or empty rows and columns
ignored by CCOLAMD and stats(3) is the number of garbage
collections performed on the internal data structure used by CCOLAMD
(roughly of size 2.2 * nnz (S) + 4 * m + 7 * n
integers).
stats(4 : 7) provide information if CCOLAMD was able to
continue. The matrix is OK if stats(4) is zero, or 1 if
invalid. stats(5) is the rightmost column index that is
unsorted or contains duplicate entries, or zero if no such column exists.
stats(6) is the last seen duplicate or out-of-order row
index in the column index given by stats(5), or zero if no
such row index exists. stats(7) is the number of duplicate
or out-of-order row indices. stats(8 : 20) is always zero in
the current version of CCOLAMD (reserved for future use).
The authors of the code itself are S. Larimore, T. Davis (Univ. of Florida) and S. Rajamanickam in collaboration with J. Bilbert and E. Ng. Supported by the National Science Foundation (DMS-9504974, DMS-9803599, CCR-0203270), and a grant from Sandia National Lab. See http://www.cise.ufl.edu/research/sparse for ccolamd, csymamd, amd, colamd, symamd, and other related orderings.
Column approximate minimum degree permutation.
p = colamd (S) returns the column approximate minimum
degree permutation vector for the sparse matrix S. For a
non-symmetric matrix S, S(:,p) tends to have
sparser LU factors than S. The Cholesky factorization of
S(:,p)' * S(:,p) also tends to be sparser
than that of S' * S.
knobs is an optional one- to three-element input vector. If S is
m-by-n, then rows with more than max(16,knobs(1)*sqrt(n))
entries are ignored. Columns with more than
max (16,knobs(2)*sqrt(min(m,n))) entries are removed prior to
ordering, and ordered last in the output permutation p. Only
completely dense rows or columns are removed if knobs(1) and
knobs(2) are < 0, respectively. If knobs(3) is
nonzero, stats and knobs are printed. The default is
knobs = [10 10 0]. Note that knobs differs from earlier
versions of colamd.
stats is an optional 20-element output vector that provides data
about the ordering and the validity of the input matrix S. Ordering
statistics are in stats(1:3). stats(1) and
stats(2) are the number of dense or empty rows and columns
ignored by COLAMD and stats(3) is the number of garbage
collections performed on the internal data structure used by COLAMD
(roughly of size 2.2 * nnz(S) + 4 * m + 7 * n
integers).
Octave built-in functions are intended to generate valid sparse matrices, with no duplicate entries, with ascending row indices of the nonzeros in each column, with a non-negative number of entries in each column (!) and so on. If a matrix is invalid, then COLAMD may or may not be able to continue. If there are duplicate entries (a row index appears two or more times in the same column) or if the row indices in a column are out of order, then COLAMD can correct these errors by ignoring the duplicate entries and sorting each column of its internal copy of the matrix S (the input matrix S is not repaired, however). If a matrix is invalid in other ways then COLAMD cannot continue, an error message is printed, and no output arguments (p or stats) are returned. COLAMD is thus a simple way to check a sparse matrix to see if it’s valid.
stats(4:7) provide information if COLAMD was able to
continue. The matrix is OK if stats(4) is zero, or 1 if
invalid. stats(5) is the rightmost column index that is
unsorted or contains duplicate entries, or zero if no such column exists.
stats(6) is the last seen duplicate or out-of-order row
index in the column index given by stats(5), or zero if no
such row index exists. stats(7) is the number of duplicate
or out-of-order row indices. stats(8:20) is always zero in
the current version of COLAMD (reserved for future use).
The ordering is followed by a column elimination tree post-ordering.
The authors of the code itself are Stefan I. Larimore and Timothy A. Davis davis@cise.ufl.edu, University of Florida. The algorithm was developed in collaboration with John Gilbert, Xerox PARC, and Esmond Ng, Oak Ridge National Laboratory. (see http://www.cise.ufl.edu/research/sparse/colamd)
Return the column permutations such that the columns of
s (:, p) are ordered in terms of increase number
of non-zero elements. If s is symmetric, then p is chosen
such that s (p, p) orders the rows and
columns with increasing number of non zeros elements.
For a symmetric positive definite matrix S, returns the permutation
vector p such that S(p,p) tends to have a
sparser Cholesky factor than S. Sometimes csymamd works
well for symmetric indefinite matrices too. The matrix S is assumed
to be symmetric; only the strictly lower triangular part is referenced.
S must be square. The ordering is followed by an elimination tree
post-ordering.
knobs is an optional 1-element to 3-element input vector, with a
default value of [10 1 0] if present or empty. Entries not
present are set to their defaults.
knobs(1)If S is n-by-n, then rows and columns with more than
max(16,knobs(1)*sqrt(n)) entries are ignored, and ordered
last in the output permutation (subject to the cmember constraints).
knobs(2)If nonzero, aggressive absorption is performed.
knobs(3)If nonzero, statistics and knobs are printed.
cmember is an optional vector of length n. It defines the constraints
on the ordering. If cmember(j) = S, then row/column j is
in constraint set c (c must be in the range 1 to n). In the
output permutation p, rows/columns in set 1 appear first, followed
by all rows/columns in set 2, and so on. cmember = ones (1,n)
if not present or empty. csymamd (S,[],1:n) returns 1:n.
p = csymamd (S) is about the same as p =
symamd (S). knobs and its default values differ.
stats(4:7) provide information if CCOLAMD was able to
continue. The matrix is OK if stats(4) is zero, or 1 if
invalid. stats(5) is the rightmost column index that is
unsorted or contains duplicate entries, or zero if no such column exists.
stats(6) is the last seen duplicate or out-of-order row
index in the column index given by stats(5), or zero if no
such row index exists. stats(7) is the number of duplicate
or out-of-order row indices. stats(8:20) is always zero in
the current version of CCOLAMD (reserved for future use).
The authors of the code itself are S. Larimore, T. Davis (Uni of Florida) and S. Rajamanickam in collaboration with J. Bilbert and E. Ng. Supported by the National Science Foundation (DMS-9504974, DMS-9803599, CCR-0203270), and a grant from Sandia National Lab. See http://www.cise.ufl.edu/research/sparse for ccolamd, csymamd, amd, colamd, symamd, and other related orderings.
Perform a Dulmage-Mendelsohn permutation of the sparse matrix S.
With a single output argument dmperm performs the row permutations
p such that S(p,:) has no zero elements on the
diagonal.
Called with two or more output arguments, returns the row and column
permutations, such that S(p, q) is in block
triangular form. The values of r and S define the boundaries
of the blocks. If S is square then r == S.
The method used is described in: A. Pothen & C.-J. Fan. Computing the Block Triangular Form of a Sparse Matrix. ACM Trans. Math. Software, 16(4):303-324, 1990.
For a symmetric positive definite matrix S, returns the permutation
vector p such that S(p, p) tends to have a
sparser Cholesky factor than S. Sometimes symamd works
well for symmetric indefinite matrices too. The matrix S is assumed
to be symmetric; only the strictly lower triangular part is referenced.
S must be square.
knobs is an optional one- to two-element input vector. If S is
n-by-n, then rows and columns with more than
max (16,knobs(1)*sqrt(n)) entries are removed prior to ordering,
and ordered last in the output permutation p. No rows/columns are
removed if knobs(1) < 0. If knobs (2) is nonzero,
stats and knobs are printed. The default is knobs
= [10 0]. Note that knobs differs from earlier versions of symamd.
stats is an optional 20-element output vector that provides data
about the ordering and the validity of the input matrix S. Ordering
statistics are in stats(1:3). stats(1) =
stats(2) is the number of dense or empty rows and columns
ignored by SYMAMD and stats(3) is the number of garbage
collections performed on the internal data structure used by SYMAMD
(roughly of size 8.4 * nnz (tril (S, -1)) + 9 * n
integers).
Octave built-in functions are intended to generate valid sparse matrices, with no duplicate entries, with ascending row indices of the nonzeros in each column, with a non-negative number of entries in each column (!) and so on. If a matrix is invalid, then SYMAMD may or may not be able to continue. If there are duplicate entries (a row index appears two or more times in the same column) or if the row indices in a column are out of order, then SYMAMD can correct these errors by ignoring the duplicate entries and sorting each column of its internal copy of the matrix S (the input matrix S is not repaired, however). If a matrix is invalid in other ways then SYMAMD cannot continue, an error message is printed, and no output arguments (p or stats) are returned. SYMAMD is thus a simple way to check a sparse matrix to see if it’s valid.
stats(4:7) provide information if SYMAMD was able to
continue. The matrix is OK if stats (4) is zero, or 1
if invalid. stats(5) is the rightmost column index that
is unsorted or contains duplicate entries, or zero if no such column
exists. stats(6) is the last seen duplicate or out-of-order
row index in the column index given by stats(5), or zero
if no such row index exists. stats(7) is the number of
duplicate or out-of-order row indices. stats(8:20) is
always zero in the current version of SYMAMD (reserved for future use).
The ordering is followed by a column elimination tree post-ordering.
The authors of the code itself are Stefan I. Larimore and Timothy A. Davis davis@cise.ufl.edu, University of Florida. The algorithm was developed in collaboration with John Gilbert, Xerox PARC, and Esmond Ng, Oak Ridge National Laboratory. (see http://www.cise.ufl.edu/research/sparse/colamd)
Return the symmetric reverse Cuthill-McKee permutation of S.
p is a permutation vector such that
S(p, p) tends to have its diagonal elements
closer to the diagonal than S. This is a good preordering for LU
or Cholesky factorization of matrices that come from “long, skinny”
problems. It works for both symmetric and asymmetric S.
The algorithm represents a heuristic approach to the NP-complete bandwidth minimization problem. The implementation is based in the descriptions found in
E. Cuthill, J. McKee. Reducing the Bandwidth of Sparse Symmetric Matrices. Proceedings of the 24th ACM National Conference, 157–172 1969, Brandon Press, New Jersey.
A. George, J.W.H. Liu. Computer Solution of Large Sparse Positive Definite Systems, Prentice Hall Series in Computational Mathematics, ISBN 0-13-165274-5, 1981.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave includes a polymorphic solver for sparse matrices, where the exact solver used to factorize the matrix, depends on the properties of the sparse matrix itself. Generally, the cost of determining the matrix type is small relative to the cost of factorizing the matrix itself, but in any case the matrix type is cached once it is calculated, so that it is not re-determined each time it is used in a linear equation.
The selection tree for how the linear equation is solve is
spparms ("bandden") continue, else goto 4.
The band density is defined as the number of non-zero values in the band
divided by the total number of values in the full band. The banded
matrix solvers can be entirely disabled by using spparms to set
bandden to 1 (i.e., spparms ("bandden", 1)).
The QR solver factorizes the problem with a Dulmage-Mendelsohn decomposition, to separate the problem into blocks that can be treated as over-determined, multiple well determined blocks, and a final over-determined block. For matrices with blocks of strongly connected nodes this is a big win as LU decomposition can be used for many blocks. It also significantly improves the chance of finding a solution to over-determined problems rather than just returning a vector of NaN’s.
All of the solvers above, can calculate an estimate of the condition number. This can be used to detect numerical stability problems in the solution and force a minimum norm solution to be used. However, for narrow banded, triangular or diagonal matrices, the cost of calculating the condition number is significant, and can in fact exceed the cost of factoring the matrix. Therefore the condition number is not calculated in these cases, and Octave relies on simpler techniques to detect singular matrices or the underlying LAPACK code in the case of banded matrices.
The user can force the type of the matrix with the matrix_type
function. This overcomes the cost of discovering the type of the matrix.
However, it should be noted that identifying the type of the matrix incorrectly
will lead to unpredictable results, and so matrix_type should be
used with care.
Estimate the 2-norm of the matrix A using a power series
analysis. This is typically used for large matrices, where the cost
of calculating norm (A) is prohibitive and an approximation
to the 2-norm is acceptable.
tol is the tolerance to which the 2-norm is calculated. By default
tol is 1e-6. c returns the number of iterations needed for
normest to converge.
Apply Higham and Tisseur’s randomized block 1-norm estimator to matrix A using t test vectors. If t exceeds 5, then only 5 test vectors are used.
If the matrix is not explicit, e.g., when estimating the norm of
inv (A) given an LU factorization, onenormest
applies A and its conjugate transpose through a pair of functions
apply and apply_t, respectively, to a dense matrix of size
n by t. The implicit version requires an explicit dimension
n.
Returns the norm estimate est, two vectors v and
w related by norm
(w, 1) = est * norm (v, 1),
and the number of iterations iter. The number of
iterations is limited to 10 and is at least 2.
References:
Estimate the 1-norm condition number of a matrix A using t test vectors using a randomized 1-norm estimator. If t exceeds 5, then only 5 test vectors are used.
If the matrix is not explicit, e.g., when estimating the condition
number of A given an LU factorization, condest uses the
following functions:
A*x for a matrix x of size n by t.
A'*x for a matrix x of size n by t.
A \ b for a matrix b of size n by t.
A' \ b for a matrix b of size n by t.
The implicit version requires an explicit dimension n.
condest uses a randomized algorithm to approximate
the 1-norms.
condest returns the 1-norm condition estimate est and
a vector v satisfying norm (A*v, 1) == norm (A, 1) * norm
(v, 1) / est. When est is large, v is an
approximate null vector.
References:
See also: cond, norm, onenormest.
Query or set the parameters used by the sparse solvers and factorization functions. The first four calls above get information about the current settings, while the others change the current settings. The parameters are stored as pairs of keys and values, where the values are all floats and the keys are one of the following strings:
Printing level of debugging information of the solvers (default 0)
Included for compatibility. Not used. (default 1)
Included for compatibility. Not used. (default 1)
Included for compatibility. Not used. (default 0)
Included for compatibility. Not used. (default 3)
Included for compatibility. Not used. (default 3)
Included for compatibility. Not used. (default 0.5)
Flag whether the LU/QR and the ’\’ and ’/’ operators will automatically use the sparsity preserving mmd functions (default 1)
Flag whether the LU and the ’\’ and ’/’ operators will automatically use the sparsity preserving amd functions (default 1)
The pivot tolerance of the UMFPACK solvers (default 0.1)
The pivot tolerance of the UMFPACK symmetric solvers (default 0.001)
The density of non-zero elements in a banded matrix before it is treated by the LAPACK banded solvers (default 0.5)
Flag whether the UMFPACK or mmd solvers are used for the LU, ’\’ and ’/’ operations (default 1)
The value of individual keys can be set with
spparms (key, val).
The default values can be restored with the special keyword
"defaults". The special keyword "tight" can be used to
set the mmd solvers to attempt a sparser solution at the potential cost of
longer running time.
Calculate the structural rank of the sparse matrix S. Note that
only the structure of the matrix is used in this calculation based on
a Dulmage-Mendelsohn permutation to block triangular form. As such the
numerical rank of the matrix S is bounded by
sprank (S) >= rank (S). Ignoring floating point errors
sprank (S) == rank (S).
See also: dmperm.
Perform a symbolic factorization analysis on the sparse matrix S. Where
S is a complex or real sparse matrix.
Is the type of the factorization and can be one of
Factorize S. This is the default.
Factorize S' * S.
Factorize S * S'.
Factorize S'
The default is to return the Cholesky factorization for r, and if
mode is 'L', the conjugate transpose of the
Cholesky factorization is returned. The conjugate transpose version is
faster and uses less memory, but returns the same values for count,
h, parent and post outputs.
The output variables are
The row counts of the Cholesky factorization as determined by typ.
The height of the elimination tree.
The elimination tree itself.
A sparse boolean matrix whose structure is that of the Cholesky factorization as determined by typ.
For non square matrices, the user can also utilize the spaugment
function to find a least squares solution to a linear equation.
Create the augmented matrix of A.
This is given by
[c * eye(m, m), A;
A', zeros(n, n)]
|
This is related to the least squares solution of
A \ b, by
s * [ r / c; x] = [ b, zeros(n, columns(b)) ] |
where r is the residual error
r = b - A * x |
As the matrix s is symmetric indefinite it can be factorized
with lu, and the minimum norm solution can therefore be found
without the need for a qr factorization. As the residual
error will be zeros (m, m) for underdetermined
problems, and example can be
m = 11; n = 10; mn = max (m, n);
A = spdiags ([ones(mn,1), 10*ones(mn,1), -ones(mn,1)],
[-1, 0, 1], m, n);
x0 = A \ ones (m,1);
s = spaugment (A);
[L, U, P, Q] = lu (s);
x1 = Q * (U \ (L \ (P * [ones(m,1); zeros(n,1)])));
x1 = x1(end - n + 1 : end);
|
To find the solution of an overdetermined problem needs an estimate
of the residual error r and so it is more complex to formulate
a minimum norm solution using the spaugment function.
In general the left division operator is more stable and faster than
using the spaugment function.
See also: mldivide.
Finally, the function eigs can be used to calculate a limited
number of eigenvalues and eigenvectors based on a selection criteria
and likewise for svds which calculates a limited number of
singular values and vectors.
Calculate a limited number of eigenvalues and eigenvectors of A, based on a selection criteria. The number of eigenvalues and eigenvectors to calculate is given by k and defaults to 6.
By default, eigs solve the equation
where
is the corresponding eigenvector. If given the positive definite matrix
B then eigs solves the general eigenvalue equation
The argument sigma determines which eigenvalues are returned. sigma can be either a scalar or a string. When sigma is a scalar, the k eigenvalues closest to sigma are returned. If sigma is a string, it must have one of the following values.
"lm"Largest Magnitude (default).
"sm"Smallest Magnitude.
"la"Largest Algebraic (valid only for real symmetric problems).
"sa"Smallest Algebraic (valid only for real symmetric problems).
"be"Both Ends, with one more from the high-end if k is odd (valid only for real symmetric problems).
"lr"Largest Real part (valid only for complex or unsymmetric problems).
"sr"Smallest Real part (valid only for complex or unsymmetric problems).
"li"Largest Imaginary part (valid only for complex or unsymmetric problems).
"si"Smallest Imaginary part (valid only for complex or unsymmetric problems).
If opts is given, it is a structure defining possible options that
eigs should use. The fields of the opts structure are:
issymIf af is given, then flags whether the function af defines a symmetric problem. It is ignored if A is given. The default is false.
isrealIf af is given, then flags whether the function af defines a real problem. It is ignored if A is given. The default is true.
tolDefines the required convergence tolerance, calculated as
tol * norm (A). The default is eps.
maxitThe maximum number of iterations. The default is 300.
pThe number of Lanzcos basis vectors to use. More vectors will result in
faster convergence, but a greater use of memory. The optimal value of
p is problem dependent and should be in the range k to n.
The default value is 2 * k.
v0The starting vector for the algorithm. An initial vector close to the
final vector will speed up convergence. The default is for ARPACK
to randomly generate a starting vector. If specified, v0 must be
an n-by-1 vector where n = rows (A)
dispThe level of diagnostic printout (0|1|2). If disp is 0 then
diagnostics are disabled. The default value is 0.
cholBFlag if chol (B) is passed rather than B. The default is
false.
permBThe permutation vector of the Cholesky factorization of B if
cholB is true. That is chol (B(permB, permB)). The
default is 1:n.
It is also possible to represent A by a function denoted af. af must be followed by a scalar argument n defining the length of the vector argument accepted by af. af can be a function handle, an inline function, or a string. When af is a string it holds the name of the function to use.
af is a function of the form y = af (x)
where the required return value of af is determined by
the value of sigma. The four possible forms are
A * xif sigma is not given or is a string other than "sm".
A \ xif sigma is 0 or "sm".
(A - sigma * I) \ xfor the standard eigenvalue problem, where I is the identity matrix of
the same size as A.
(A - sigma * B) \ xfor the general eigenvalue problem.
The return arguments of eigs depend on the number of return arguments
requested. With a single return argument, a vector d of length k
is returned containing the k eigenvalues that have been found. With
two return arguments, V is a n-by-k matrix whose columns
are the k eigenvectors corresponding to the returned eigenvalues. The
eigenvalues themselves are returned in d in the form of a
n-by-k matrix, where the elements on the diagonal are the
eigenvalues.
Given a third return argument flag, eigs returns the status
of the convergence. If flag is 0 then all eigenvalues have converged.
Any other value indicates a failure to converge.
This function is based on the ARPACK package, written by R. Lehoucq, K. Maschhoff, D. Sorensen, and C. Yang. For more information see http://www.caam.rice.edu/software/ARPACK/.
Find a few singular values of the matrix A. The singular values are calculated using
[m, n] = size (A);
s = eigs ([sparse(m, m), A;
A', sparse(n, n)])
|
The eigenvalues returned by eigs correspond to the singular values
of A. The number of singular values to calculate is given by k
and defaults to 6.
The argument sigma specifies which singular values to find. When
sigma is the string 'L', the default, the largest singular
values of A are found. Otherwise, sigma must be a real scalar
and the singular values closest to sigma are found. As a corollary,
sigma = 0 finds the smallest singular values. Note that for
relatively small values of sigma, there is a chance that the
requested number of singular values will not be found. In that case
sigma should be increased.
opts is a structure defining options that svds will pass
to eigs. The possible fields of this structure are documented in
eigs. By default, svds sets the following three fields:
tolThe required convergence tolerance for the singular values. The default
value is 1e-10. eigs is passed tol / sqrt(2).
maxitThe maximum number of iterations. The default is 300.
dispThe level of diagnostic printout (0|1|2). If disp is 0 then
diagnostics are disabled. The default value is 0.
If more than one output is requested then svds will return an
approximation of the singular value decomposition of A
A_approx = u*s*v' |
where A_approx is a matrix of size A but only rank k.
flag returns 0 if the algorithm has succesfully converged, and 1 otherwise. The test for convergence is
norm (A*v - u*s, 1) <= tol * norm (A, 1) |
svds is best for finding only a few singular values from a large
sparse matrix. Otherwise, svd (full (A)) will likely be more
efficient.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The left division \ and right division / operators,
discussed in the previous section, use direct solvers to resolve a
linear equation of the form x = A \ b or
x = b / A. Octave equally includes a number of
functions to solve sparse linear equations using iterative techniques.
Solve the linear system of equations A * x = b
by means of the Preconditioned Conjugate Gradient iterative method. The
input arguments are
A * x. In principle, A should be
symmetric and positive definite; if pcg finds A not to be
positive definite, a warning is printed and the flag output will be
set.
b - A * x. The iteration stops if
norm (b - A * x) ≤
tol * norm (b).
If tol is omitted or empty then a tolerance of 1e-6 is used.
pcg
P * x = m \ b, with
P = m \ A.
Note that a proper choice of the preconditioner may dramatically
improve the overall performance of the method. Instead of matrices
m1 and m2, the user may pass two functions which return
the results of applying the inverse of m1 and m2 to
a vector (usually this is the preferred way of using the preconditioner).
If m1 is omitted or empty [] then no preconditioning is
applied. If m2 is omitted, m = m1 will be used as
a preconditioner.
The arguments which follow x0 are treated as parameters, and passed in
a proper way to any of the functions (A or m) which are passed
to pcg. See the examples below for further details. The output
arguments are
A * x = b.
resvec(i,1) is the Euclidean norm of the residual, and
resvec(i,2) is the preconditioned residual norm, after the
(i-1)-th iteration, i = 1, 2, …, iter+1.
The preconditioned residual norm is defined as
norm (r) ^ 2 = r' * (m \ r) where
r = b - A * x, see also the
description of m. If eigest is not required, only
resvec(:,1) is returned.
eigest(1)
and largest eigest(2) eigenvalues of the preconditioned matrix
P = m \ A. In particular, if no
preconditioning is used, the estimates for the extreme eigenvalues of
A are returned. eigest(1) is an overestimate and
eigest(2) is an underestimate, so that
eigest(2) / eigest(1) is a lower bound for
cond (P, 2), which nevertheless in the limit should
theoretically be equal to the actual value of the condition number.
The method which computes eigest works only for symmetric positive
definite A and m, and the user is responsible for verifying this
assumption.
Let us consider a trivial problem with a diagonal matrix (we exploit the sparsity of A)
n = 10; A = diag (sparse (1:n)); b = rand (n, 1); [l, u, p, q] = luinc (A, 1.e-3); |
EXAMPLE 1: Simplest use of pcg
x = pcg (A, b) |
EXAMPLE 2: pcg with a function which computes
A * x
function y = apply_a (x)
y = [1:N]' .* x;
endfunction
x = pcg ("apply_a", b)
|
EXAMPLE 3: pcg with a preconditioner: l * u
x = pcg (A, b, 1.e-6, 500, l*u) |
EXAMPLE 4: pcg with a preconditioner: l * u.
Faster than EXAMPLE 3 since lower and upper triangular matrices
are easier to invert
x = pcg (A, b, 1.e-6, 500, l, u) |
EXAMPLE 5: Preconditioned iteration, with full diagnostics. The preconditioner (quite strange, because even the original matrix A is trivial) is defined as a function
function y = apply_m (x)
k = floor (length (x) - 2);
y = x;
y(1:k) = x(1:k) ./ [1:k]';
endfunction
[x, flag, relres, iter, resvec, eigest] = ...
pcg (A, b, [], [], "apply_m");
semilogy (1:iter+1, resvec);
|
EXAMPLE 6: Finally, a preconditioner which depends on a parameter k.
function y = apply_M (x, varargin)
K = varargin{1};
y = x;
y(1:K) = x(1:K) ./ [1:K]';
endfunction
[x, flag, relres, iter, resvec, eigest] = ...
pcg (A, b, [], [], "apply_m", [], [], 3)
|
References:
Solve the linear system of equations A * x = b
by means of the Preconditioned Conjugate Residuals iterative
method. The input arguments are
A * x. In principle
A should be symmetric and non-singular; if pcr
finds A to be numerically singular, you will get a warning
message and the flag output parameter will be set.
b - A * x. The iteration stops if
norm (b - A * x) <=
tol * norm (b - A * x0).
If tol is empty or is omitted, the function sets
tol = 1e-6 by default.
[] is supplied for maxit, or pcr has less
arguments, a default value equal to 20 is used.
pcr P *
x = m \ b, with P = m \ A.
Note that a proper choice of the preconditioner may dramatically
improve the overall performance of the method. Instead of matrix
m, the user may pass a function which returns the results of
applying the inverse of m to a vector (usually this is the
preferred way of using the preconditioner). If [] is supplied
for m, or m is omitted, no preconditioning is applied.
The arguments which follow x0 are treated as parameters, and
passed in a proper way to any of the functions (A or m)
which are passed to pcr. See the examples below for further
details. The output arguments are
A * x = b.
flag = 0 means
the solution converged and the tolerance criterion given by tol
is satisfied. flag = 1 means that the maxit limit
for the iteration count was reached. flag = 3 reports t
pcr breakdown, see [1] for details.
resvec (i) contains the Euclidean norms of the
residual after the (i-1)-th iteration, i =
1,2, …, iter+1.
Let us consider a trivial problem with a diagonal matrix (we exploit the sparsity of A)
n = 10; A = sparse (diag (1:n)); b = rand (N, 1); |
EXAMPLE 1: Simplest use of pcr
x = pcr (A, b) |
EXAMPLE 2: pcr with a function which computes
A * x.
function y = apply_a (x)
y = [1:10]' .* x;
endfunction
x = pcr ("apply_a", b)
|
EXAMPLE 3: Preconditioned iteration, with full diagnostics. The preconditioner (quite strange, because even the original matrix A is trivial) is defined as a function
function y = apply_m (x)
k = floor (length (x) - 2);
y = x;
y(1:k) = x(1:k) ./ [1:k]';
endfunction
[x, flag, relres, iter, resvec] = ...
pcr (A, b, [], [], "apply_m")
semilogy ([1:iter+1], resvec);
|
EXAMPLE 4: Finally, a preconditioner which depends on a parameter k.
function y = apply_m (x, varargin)
k = varargin{1};
y = x;
y(1:k) = x(1:k) ./ [1:k]';
endfunction
[x, flag, relres, iter, resvec] = ...
pcr (A, b, [], [], "apply_m"', [], 3)
|
References:
[1] W. Hackbusch, Iterative Solution of Large Sparse Systems of Equations, section 9.5.4; Springer, 1994
The speed with which an iterative solver converges to a solution can be
accelerated with the use of a pre-conditioning matrix M. In this
case the linear equation M^-1 * x = M^-1 *
A \ b is solved instead. Typical pre-conditioning matrices
are partial factorizations of the original matrix.
Produce the incomplete LU factorization of the sparse matrix A.
Two types of incomplete factorization are possible, and the type
is determined by the second argument to luinc.
Called with a second argument of '0', the zero-level incomplete
LU factorization is produced. This creates a factorization of A
where the position of the non-zero arguments correspond to the same
positions as in the matrix A.
Alternatively, the fill-in of the incomplete LU factorization can be controlled through the variable droptol or the structure opts. The UMFPACK multifrontal factorization code by Tim A. Davis is used for the incomplete LU factorization, (availability http://www.cise.ufl.edu/research/sparse/umfpack/)
droptol determines the values below which the values in the LU factorization are dropped and replaced by zero. It must be a positive scalar, and any values in the factorization whose absolute value are less than this value are dropped, expect if leaving them increase the sparsity of the matrix. Setting droptol to zero results in a complete LU factorization which is the default.
opts is a structure containing one or more of the fields
droptolThe drop tolerance as above. If opts only contains droptol
then this is equivalent to using the variable droptol.
miluA logical variable flagging whether to use the modified incomplete
LU factorization. In the case that milu is true, the dropped
values are subtracted from the diagonal of the matrix U of the
factorization. The default is false.
udiagA logical variable that flags whether zero elements on the diagonal of
U should be replaced with droptol to attempt to avoid singular
factors. The default is false.
threshDefines the pivot threshold in the interval [0,1]. Values outside that range are ignored.
All other fields in opts are ignored. The outputs from luinc
are the same as for lu.
Given the string argument "vector", luinc returns the
values of p q as vector values.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A common application for sparse matrices is in the solution of Finite Element Models. Finite element models allow numerical solution of partial differential equations that do not have closed form solutions, typically because of the complex shape of the domain.
In order to motivate this application, we consider the boundary value Laplace equation. This system can model scalar potential fields, such as heat or electrical potential. Given a medium Omega with boundary dOmega. At all points on the dOmega the boundary conditions are known, and we wish to calculate the potential in Omega. Boundary conditions may specify the potential (Dirichlet boundary condition), its normal derivative across the boundary (Neumann boundary condition), or a weighted sum of the potential and its derivative (Cauchy boundary condition).
In a thermal model, we want to calculate the temperature in Omega and know the boundary temperature (Dirichlet condition) or heat flux (from which we can calculate the Neumann condition by dividing by the thermal conductivity at the boundary). Similarly, in an electrical model, we want to calculate the voltage in Omega and know the boundary voltage (Dirichlet) or current (Neumann condition after diving by the electrical conductivity). In an electrical model, it is common for much of the boundary to be electrically isolated; this is a Neumann boundary condition with the current equal to zero.
The simplest finite element models will divide
Omega
into simplexes (triangles in 2D, pyramids in 3D).
We take as a 3-D example a cylindrical liquid filled tank with a small
non-conductive ball from the EIDORS project(11). This is model is designed to reflect
an application of electrical impedance tomography, where current patterns
are applied to such a tank in order to image the internal conductivity
distribution. In order to describe the FEM geometry, we have a matrix of
vertices nodes and simplices elems.
The following example creates a simple rectangular 2-D electrically conductive medium with 10 V and 20 V imposed on opposite sides (Dirichlet boundary conditions). All other edges are electrically isolated.
node_y = [1;1.2;1.5;1.8;2]*ones(1,11);
node_x = ones(5,1)*[1,1.05,1.1,1.2, ...
1.3,1.5,1.7,1.8,1.9,1.95,2];
nodes = [node_x(:), node_y(:)];
[h,w] = size (node_x);
elems = [];
for idx = 1:w-1
widx = (idx-1)*h;
elems = [elems; ...
widx+[(1:h-1);(2:h);h+(1:h-1)]'; ...
widx+[(2:h);h+(2:h);h+(1:h-1)]' ];
endfor
E = size (elems,1); # No. of simplices
N = size (nodes,1); # No. of vertices
D = size (elems,2); # dimensions+1
|
This creates a N-by-2 matrix nodes and a E-by-3 matrix
elems with values, which define finite element triangles:
nodes(1:7,:)'
1.00 1.00 1.00 1.00 1.00 1.05 1.05 …
1.00 1.20 1.50 1.80 2.00 1.00 1.20 …
elems(1:7,:)'
1 2 3 4 2 3 4 …
2 3 4 5 7 8 9 …
6 7 8 9 6 7 8 …
|
Using a first order FEM, we approximate the electrical conductivity
distribution in
Omega
as constant on each simplex (represented by the vector conductivity).
Based on the finite element geometry, we first calculate a system (or
stiffness) matrix for each simplex (represented as 3-by-3 elements on the
diagonal of the element-wise system matrix SE. Based on SE
and a N-by-DE connectivity matrix C, representing the connections
between simplices and vertices, the global connectivity matrix S is
calculated.
## Element conductivity
conductivity = [1*ones(1,16), ...
2*ones(1,48), 1*ones(1,16)];
## Connectivity matrix
C = sparse ((1:D*E), reshape (elems', ...
D*E, 1), 1, D*E, N);
## Calculate system matrix
Siidx = floor ([0:D*E-1]'/D) * D * ...
ones(1,D) + ones(D*E,1)*(1:D) ;
Sjidx = [1:D*E]'*ones (1,D);
Sdata = zeros (D*E,D);
dfact = factorial (D-1);
for j = 1:E
a = inv ([ones(D,1), ...
nodes(elems(j,:), :)]);
const = conductivity(j) * 2 / ...
dfact / abs (det (a));
Sdata(D*(j-1)+(1:D),:) = const * ...
a(2:D,:)' * a(2:D,:);
endfor
## Element-wise system matrix
SE = sparse(Siidx,Sjidx,Sdata);
## Global system matrix
S = C'* SE *C;
|
The system matrix acts like the conductivity
S
in Ohm’s law
S * V = I.
Based on the Dirichlet and Neumann boundary conditions, we are able to
solve for the voltages at each vertex V.
## Dirichlet boundary conditions
D_nodes = [1:5, 51:55];
D_value = [10*ones(1,5), 20*ones(1,5)];
V = zeros (N,1);
V(D_nodes) = D_value;
idx = 1:N; # vertices without Dirichlet
# boundary condns
idx(D_nodes) = [];
## Neumann boundary conditions. Note that
## N_value must be normalized by the
## boundary length and element conductivity
N_nodes = [];
N_value = [];
Q = zeros (N,1);
Q(N_nodes) = N_value;
V(idx) = S(idx,idx) \ ( Q(idx) - ...
S(idx,D_nodes) * V(D_nodes));
|
Finally, in order to display the solution, we show each solved voltage value in the z-axis for each simplex vertex. See fig:femmodel.
elemx = elems(:,[1,2,3,1])'; xelems = reshape (nodes(elemx, 1), 4, E); yelems = reshape (nodes(elemx, 2), 4, E); velems = reshape (V(elemx), 4, E); plot3 (xelems,yelems,velems,"k"); print "grid.eps"; |
Figure 22.6: Example finite element model the showing triangular elements. The height of each vertex corresponds to the solution value.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave comes with several built-in functions for computing the integral of a function numerically (termed quadrature). These functions all solve 1-dimensional integration problems.
| 23.1 Functions of One Variable | ||
| 23.2 Orthogonal Collocation | ||
| 23.3 Functions of Multiple Variables |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave supports five different algorithms for computing the integral of a function f over the interval from a to b. These are
quadNumerical integration based on Gaussian quadrature.
quadvNumerical integration using an adaptive vectorized Simpson’s rule.
quadlNumerical integration using an adaptive Lobatto rule.
quadgkNumerical integration using an adaptive Gauss-Konrod rule.
quadccNumerical integration using adaptive Clenshaw-Curtis rules.
trapz, cumtrapzNumerical integration of data using the trapezoidal method.
The best quadrature algorithm to use depends on the integrand. If you have
empirical data, rather than a function, the choice is trapz or
cumtrapz. If you are uncertain about the characteristics of the
integrand, quadcc will be the most robust as it can handle
discontinuities, singularities, oscillatory functions, and infinite intervals.
When the integrand is smooth quadgk may be the fastest of the
algorithms.
| Function | Characteristics | |
|---|---|---|
| quad | Low accuracy with nonsmooth integrands | |
| quadv | Medium accuracy with smooth integrands | |
| quadl | Medium accuracy with smooth integrands. Slower than quadgk. | |
| quadgk | Medium accuracy (1e^-6–1e^-9) with smooth integrands. | |
| Handles oscillatory functions and infinite bounds | ||
| quadcc | Low to High accuracy with nonsmooth/smooth integrands | |
| Handles oscillatory functions, singularities, and infinite bounds |
Here is an example of using quad to integrate the function
f(x) = x * sin (1/x) * sqrt (abs (1 - x)) |
from x = 0 to x = 3.
This is a fairly difficult integration (plot the function over the range of integration to see why).
The first step is to define the function:
function y = f (x) y = x .* sin (1./x) .* sqrt (abs (1 - x)); endfunction |
Note the use of the ‘dot’ forms of the operators. This is not necessary for
the quad integrator, but is required by the other integrators. In any
case, it makes it much easier to generate a set of points for plotting because
it is possible to call the function with a vector argument to produce a vector
result.
The second step is to call quad with the limits of integration:
[q, ier, nfun, err] = quad ("f", 0, 3)
⇒ 1.9819
⇒ 1
⇒ 5061
⇒ 1.1522e-07
|
Although quad returns a nonzero value for ier, the result
is reasonably accurate (to see why, examine what happens to the result
if you move the lower bound to 0.1, then 0.01, then 0.001, etc.).
The function "f" can be the string name of a function, a function
handle, or an inline function. These options make it quite easy to do
integration without having to fully define a function in an m-file. For
example:
# Verify integral (x^3) = x^4/4
f = inline ("x.^3");
quadgk (f, 0, 1)
⇒ 0.25000
# Verify gamma function = (n-1)! for n = 4
f = @(x) x.^3 .* exp (-x);
quadcc (f, 0, Inf)
⇒ 6.0000
|
Numerically evaluate the integral of f from a to b using
Fortran routines from QUADPACK. f is a function handle,
inline function, or a string containing the name of the function to
evaluate. The function must have the form y = f (x) where y and
x are scalars.
a and b are the lower and upper limits of integration. Either or both may be infinite.
The optional argument tol is a vector that specifies the desired
accuracy of the result. The first element of the vector is the desired
absolute tolerance, and the second element is the desired relative
tolerance. To choose a relative test only, set the absolute
tolerance to zero. To choose an absolute test only, set the relative
tolerance to zero. Both tolerances default to sqrt (eps) or
approximately 1.5e^-8.
The optional argument sing is a vector of values at which the integrand is known to be singular.
The result of the integration is returned in q. ier contains an integer error code (0 indicates a successful integration). nfun indicates the number of function evaluations that were made, and err contains an estimate of the error in the solution.
The function quad_options can set other optional
parameters for quad.
Note: because quad is written in Fortran it cannot be called
recursively. This prevents its use in integrating over more than one
variable by routines dblquad and triplequad.
See also: quad_options, quadv, quadl, quadgk, quadcc, trapz, dblquad, triplequad.
Query or set options for the function quad.
When called with no arguments, the names of all available options and
their current values are displayed.
Given one argument, return the value of the corresponding option.
When called with two arguments, quad_options set the option
opt to value val.
Options include
"absolute tolerance"Absolute tolerance; may be zero for pure relative error test.
"relative tolerance"Non-negative relative tolerance. If the absolute tolerance is zero,
the relative tolerance must be greater than or equal to
max (50*eps, 0.5e-28).
"single precision absolute tolerance"Absolute tolerance for single precision; may be zero for pure relative error test.
"single precision relative tolerance"Non-negative relative tolerance for single precision. If the absolute
tolerance is zero, the relative tolerance must be greater than or equal to
max (50*eps, 0.5e-28).
Numerically evaluate the integral of f from a to b
using an adaptive Simpson’s rule.
f is a function handle, inline function, or string
containing the name of the function to evaluate.
quadv is a vectorized version of quad and the function
defined by f must accept a scalar or vector as input and return a
scalar, vector, or array as output.
a and b are the lower and upper limits of integration. Both limits must be finite.
The optional argument tol defines the tolerance used to stop the adaptation procedure. The default value is 1e^-6.
The algorithm used by quadv involves recursively subdividing the
integration interval and applying Simpson’s rule on each subinterval.
If trace is true then after computing each of these partial
integrals display: (1) the total number of function evaluations,
(2) the left end of the subinterval, (3) the length of the subinterval,
(4) the approximation of the integral over the subinterval.
Additional arguments p1, etc., are passed directly to the function f. To use default values for tol and trace, one may pass empty matrices ([]).
The result of the integration is returned in q. nfun indicates the number of function evaluations that were made.
Note: quadv is written in Octave’s scripting language and can be
used recursively in dblquad and triplequad, unlike the
similar quad function.
See also: quad, quadl, quadgk, quadcc, trapz, dblquad, triplequad.
Numerically evaluate the integral of f from a to b using an adaptive Lobatto rule. f is a function handle, inline function, or string containing the name of the function to evaluate. The function f must be vectorized and return a vector of output values if given a vector of input values.
a and b are the lower and upper limits of integration. Both limits must be finite.
The optional argument tol defines the relative tolerance with which
to perform the integration. The default value is eps.
The algorithm used by quadl involves recursively subdividing the
integration interval.
If trace is defined then for each subinterval display: (1) the left
end of the subinterval, (2) the length of the subinterval, (3) the
approximation of the integral over the subinterval.
Additional arguments p1, etc., are passed directly to the function f. To use default values for tol and trace, one may pass empty matrices ([]).
Reference: W. Gander and W. Gautschi, Adaptive Quadrature - Revisited, BIT Vol. 40, No. 1, March 2000, pp. 84–101. http://www.inf.ethz.ch/personal/gander/
See also: quad, quadv, quadgk, quadcc, trapz, dblquad, triplequad.
Numerically evaluate the integral of f from a to b using adaptive Gauss-Konrod quadrature. f is a function handle, inline function, or string containing the name of the function to evaluate. The formulation is based on a proposal by L.F. Shampine, "Vectorized adaptive quadrature in MATLAB", Journal of Computational and Applied Mathematics, pp131-140, Vol 211, Issue 2, Feb 2008 where all function evaluations at an iteration are calculated with a single call to f. Therefore, the function f must be vectorized and must accept a vector of input values x and return an output vector representing the function evaluations at the given values of x.
a and b are the lower and upper limits of integration. Either or both limits may be infinite or contain weak end singularities. Variable transformation will be used to treat any infinite intervals and weaken the singularities. For example:
quadgk (@(x) 1 ./ (sqrt (x) .* (x + 1)), 0, Inf) |
Note that the formulation of the integrand uses the
element-by-element operator ./ and all user functions to
quadgk should do the same.
The optional argument tol defines the absolute tolerance used to stop the integration procedure. The default value is 1e^-10.
The algorithm used by quadgk involves subdividing the
integration interval and evaluating each subinterval.
If trace is true then after computing each of these partial
integrals display: (1) the number of subintervals at this step,
(2) the current estimate of the error err, (3) the current estimate
for the integral q.
Alternatively, properties of quadgk can be passed to the function as
pairs "prop", val. Valid properties are
AbsTolDefine the absolute error tolerance for the quadrature. The default absolute tolerance is 1e-10.
RelTolDefine the relative error tolerance for the quadrature. The default relative tolerance is 1e-5.
MaxIntervalCountquadgk initially subdivides the interval on which to perform
the quadrature into 10 intervals. Subintervals that have an
unacceptable error are subdivided and re-evaluated. If the number of
subintervals exceeds 650 subintervals at any point then a poor
convergence is signaled and the current estimate of the integral is
returned. The property "MaxIntervalCount" can be used to alter the
number of subintervals that can exist before exiting.
WayPointsDiscontinuities in the first derivative of the function to integrate can be
flagged with the "WayPoints" property. This forces the ends of
a subinterval to fall on the breakpoints of the function and can result in
significantly improved estimation of the error in the integral, faster
computation, or both. For example,
quadgk (@(x) abs (1 - x.^2), 0, 2, "Waypoints", 1) |
signals the breakpoint in the integrand at x = 1.
TraceIf logically true quadgk prints information on the
convergence of the quadrature at each iteration.
If any of a, b, or waypoints is complex then the quadrature is treated as a contour integral along a piecewise continuous path defined by the above. In this case the integral is assumed to have no edge singularities. For example,
quadgk (@(z) log (z), 1+1i, 1+1i, "WayPoints",
[1-1i, -1,-1i, -1+1i])
|
integrates log (z) along the square defined by [1+1i,
1-1i, -1-1i, -1+1i]
The result of the integration is returned in q.
err is an approximate bound on the error in the integral
abs (q - I), where I is the exact value of the
integral.
See also: quad, quadv, quadl, quadcc, trapz, dblquad, triplequad.
Numerically evaluate the integral of f from a to b using the doubly-adaptive Clenshaw-Curtis quadrature described by P. Gonnet in Increasing the Reliability of Adaptive Quadrature Using Explicit Interpolants. f is a function handle, inline function, or string containing the name of the function to evaluate. The function f must be vectorized and must return a vector of output values if given a vector of input values. For example,
f = @(x) x .* sin (1./x) .* sqrt (abs (1 - x)); |
which uses the element-by-element “dot” form for all operators.
a and b are the lower and upper limits of integration. Either
or both limits may be infinite. quadcc handles an inifinite limit
by substituting the variable of integration with x = tan (pi/2*u).
The optional argument tol defines the relative tolerance used to stop the integration procedure. The default value is 1e^-6.
The optional argument sing contains a list of points where the
integrand has known singularities, or discontinuities
in any of its derivatives, inside the integration interval.
For the example above, which has a discontinuity at x=1, the call to
quadcc would be as follows
int = quadcc (f, a, b, 1.0e-6, [ 1 ]); |
The result of the integration is returned in q. err is an estimate of the absolute integration error and nr_points is the number of points at which the integrand was evaluated. If the adaptive integration did not converge, the value of err will be larger than the requested tolerance. Therefore, it is recommended to verify this value for difficult integrands.
quadcc is capable of dealing with non-numeric
values of the integrand such as NaN or Inf.
If the integral diverges, and quadcc detects this,
then a warning is issued and Inf or -Inf is returned.
Note: quadcc is a general purpose quadrature algorithm
and, as such, may be less efficient for a smooth or otherwise
well-behaved integrand than other methods such as quadgk.
The algorithm uses Clenshaw-Curtis quadrature rules of increasing degree in each interval and bisects the interval if either the function does not appear to be smooth or a rule of maximum degree has been reached. The error estimate is computed from the L2-norm of the difference between two successive interpolations of the integrand over the nodes of the respective quadrature rules.
Reference: P. Gonnet, Increasing the Reliability of Adaptive Quadrature Using Explicit Interpolants, ACM Transactions on Mathematical Software, Vol. 37, Issue 3, Article No. 3, 2010.
See also: quad, quadv, quadl, quadgk, trapz, dblquad, triplequad.
Sometimes one does not have the function, but only the raw (x, y) points from
which to perform an integration. This can occur when collecting data in an
experiment. The trapz function can integrate these values as shown in
the following example where "data" has been collected on the cosine function
over the range [0, pi/2).
x = 0:0.1:pi/2; # Uniformly spaced points
y = cos (x);
trapz (x, y)
⇒ 0.99666
|
The answer is reasonably close to the exact value of 1. Ordinary quadrature is sensitive to the characteristics of the integrand. Empirical integration depends not just on the integrand, but also on the particular points chosen to represent the function. Repeating the example above with the sine function over the range [0, pi/2) produces far inferior results.
x = 0:0.1:pi/2; # Uniformly spaced points
y = sin (x);
trapz (x, y)
⇒ 0.92849
|
However, a slightly different choice of data points can change the result significantly. The same integration, with the same number of points, but spaced differently produces a more accurate answer.
x = linspace (0, pi/2, 16); # Uniformly spaced, but including endpoint
y = sin (x);
trapz (x, y)
⇒ 0.99909
|
In general there may be no way of knowing the best distribution of points ahead
of time. Or the points may come from an experiment where there is no freedom to
select the best distribution. In any case, one must remain aware of this
issue when using trapz.
Numerically evaluate the integral of points y using the trapezoidal
method.
trapz (y) computes the integral of y along the first
non-singleton dimension. When the argument x is omitted an
equally spaced x vector with unit spacing (1) is assumed.
trapz (x, y) evaluates the integral with respect
to the spacing in x and the values in y. This is useful if
the points in y have been sampled unevenly.
If the optional dim argument is given, operate along this dimension.
If x is not specified then unit spacing will be used. To scale
the integral to the correct value you must multiply by the actual spacing
value (deltaX). As an example, the integral of x^3 over the range
[0, 1] is x^4/4 or 0.25. The following code uses trapz to
calculate the integral in three different ways.
x = 0:0.1:1; y = x.^3; q = trapz (y) ⇒ q = 2.525 # No scaling q * 0.1 ⇒ q = 0.2525 # Approximation to integral by scaling trapz (x, y) ⇒ q = 0.2525 # Same result by specifying x |
See also: cumtrapz.
Cumulative numerical integration of points y using the trapezoidal
method.
cumtrapz (y) computes the cumulative integral of y
along the first non-singleton dimension. Where trapz reports
only the overall integral sum, cumtrapz reports the current partial
sum value at each point of y. When the argument x is omitted
an equally spaced x vector with unit spacing (1) is assumed.
cumtrapz (x, y) evaluates the integral with respect to
the spacing in x and the values in y. This is useful if the
points in y have been sampled unevenly. If the optional dim
argument is given, operate along this dimension.
If x is not specified then unit spacing will be used. To scale the integral to the correct value you must multiply by the actual spacing value (deltaX).
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Compute derivative and integral weight matrices for orthogonal collocation using the subroutines given in J. Villadsen and M. L. Michelsen, Solution of Differential Equation Models by Polynomial Approximation.
Here is an example of using colloc to generate weight matrices
for solving the second order differential equation
u’ - alpha * u” = 0 with the boundary conditions
u(0) = 0 and u(1) = 1.
First, we can generate the weight matrices for n points (including the endpoints of the interval), and incorporate the boundary conditions in the right hand side (for a specific value of alpha).
n = 7; alpha = 0.1; [r, a, b] = colloc (n-2, "left", "right"); at = a(2:n-1,2:n-1); bt = b(2:n-1,2:n-1); rhs = alpha * b(2:n-1,n) - a(2:n-1,n); |
Then the solution at the roots r is
u = [ 0; (at - alpha * bt) \ rhs; 1]
⇒ [ 0.00; 0.004; 0.01 0.00; 0.12; 0.62; 1.00 ]
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave does not have built-in functions for computing the integral of functions of multiple variables directly. It is possible, however, to compute the integral of a function of multiple variables using the existing functions for one-dimensional integrals.
To illustrate how the integration can be performed, we will integrate the function
f(x, y) = sin(pi*x*y)*sqrt(x*y) |
for x and y between 0 and 1.
The first approach creates a function that integrates f with
respect to x, and then integrates that function with respect to
y. Because quad is written in Fortran it cannot be called
recursively. This means that quad cannot integrate a function
that calls quad, and hence cannot be used to perform the double
integration. Any of the other integrators, however, can be used which is
what the following code demonstrates.
function q = g(y)
q = ones (size (y));
for i = 1:length (y)
f = @(x) sin (pi*x.*y(i)) .* sqrt (x.*y(i));
q(i) = quadgk (f, 0, 1);
endfor
endfunction
I = quadgk ("g", 0, 1)
⇒ 0.30022
|
The above process can be simplified with the dblquad and
triplequad functions for integrals over two and three
variables. For example:
I = dblquad (@(x, y) sin (pi*x.*y) .* sqrt (x.*y), 0, 1, 0, 1)
⇒ 0.30022
|
Numerically evaluate the double integral of f. f is a function handle, inline function, or string containing the name of the function to evaluate. The function f must have the form z = f(x,y) where x is a vector and y is a scalar. It should return a vector of the same length and orientation as x.
xa, ya and xb, yb are the lower and upper limits of integration for x and y respectively. The underlying integrator determines whether infinite bounds are accepted.
The optional argument tol defines the absolute tolerance used to integrate each sub-integral. The default value is 1e^-6.
The optional argument quadf specifies which underlying integrator
function to use. Any choice but quad is available and the default
is quadcc.
Additional arguments, are passed directly to f. To use the default
value for tol or quadf one may pass ':' or an empty
matrix ([]).
See also: triplequad, quad, quadv, quadl, quadgk, quadcc, trapz.
Numerically evaluate the triple integral of f. f is a function handle, inline function, or string containing the name of the function to evaluate. The function f must have the form w = f(x,y,z) where either x or y is a vector and the remaining inputs are scalars. It should return a vector of the same length and orientation as x or y.
xa, ya, za and xb, yb, zb are the lower and upper limits of integration for x, y, and z respectively. The underlying integrator determines whether infinite bounds are accepted.
The optional argument tol defines the absolute tolerance used to integrate each sub-integral. The default value is 1e^-6.
The optional argument quadf specifies which underlying integrator
function to use. Any choice but quad is available and the default
is quadcc.
Additional arguments, are passed directly to f. To use the default
value for tol or quadf one may pass ':' or an empty
matrix ([]).
See also: dblquad, quad, quadv, quadl, quadgk, quadcc, trapz.
The above mentioned approach works, but is fairly slow, and that problem
increases exponentially with the dimensionality of the integral. Another
possible solution is to use Orthogonal Collocation as described in the
previous section (see section Orthogonal Collocation). The integral of a function
f(x,y) for x and y between 0 and 1 can be approximated
using n points by
the sum over i=1:n and j=1:n of q(i)*q(j)*f(r(i),r(j)),
where q and r is as returned by colloc (n). The
generalization to more than two variables is straight forward. The
following code computes the studied integral using n=8 points.
f = @(x,y) sin (pi*x*y') .* sqrt (x*y');
n = 8;
[t, ~, ~, q] = colloc (n);
I = q'*f(t,t)*q;
⇒ 0.30022
|
It should be noted that the number of points determines the quality of the approximation. If the integration needs to be performed between a and b, instead of 0 and 1, then a change of variables is needed.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave has built-in functions for solving ordinary differential equations, and differential-algebraic equations. All solvers are based on reliable ODE routines written in Fortran.
| 24.1 Ordinary Differential Equations | ||
| 24.2 Differential-Algebraic Equations |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The function lsode can be used to solve ODEs of the form
dx -- = f (x, t) dt |
using Hindmarsh’s ODE solver LSODE.
Solve the set of differential equations
dx -- = f (x, t) dt |
with
x(t_0) = x_0 |
The solution is returned in the matrix x, with each row corresponding to an element of the vector t. The first element of t should be t_0 and should correspond to the initial state of the system x_0, so that the first row of the output is x_0.
The first argument, fcn, is a string, inline, or function handle that names the function f to call to compute the vector of right hand sides for the set of equations. The function must have the form
xdot = f (x, t) |
in which xdot and x are vectors and t is a scalar.
If fcn is a two-element string array or a two-element cell array of strings, inline functions, or function handles, the first element names the function f described above, and the second element names a function to compute the Jacobian of f. The Jacobian function must have the form
jac = j (x, t) |
in which jac is the matrix of partial derivatives
| df_1 df_1 df_1 |
| ---- ---- ... ---- |
| dx_1 dx_2 dx_N |
| |
| df_2 df_2 df_2 |
| ---- ---- ... ---- |
df_i | dx_1 dx_2 dx_N |
jac = ---- = | |
dx_j | . . . . |
| . . . . |
| . . . . |
| |
| df_N df_N df_N |
| ---- ---- ... ---- |
| dx_1 dx_2 dx_N |
|
The second and third arguments specify the initial state of the system, x_0, and the initial value of the independent variable t_0.
The fourth argument is optional, and may be used to specify a set of times that the ODE solver should not integrate past. It is useful for avoiding difficulties with singularities and points where there is a discontinuity in the derivative.
After a successful computation, the value of istate will be 2 (consistent with the Fortran version of LSODE).
If the computation is not successful, istate will be something other than 2 and msg will contain additional information.
You can use the function lsode_options to set optional
parameters for lsode.
Query or set options for the function lsode.
When called with no arguments, the names of all available options and
their current values are displayed.
Given one argument, return the value of the corresponding option.
When called with two arguments, lsode_options set the option
opt to value val.
Options include
"absolute tolerance"Absolute tolerance. May be either vector or scalar. If a vector, it must match the dimension of the state vector.
"relative tolerance"Relative tolerance parameter. Unlike the absolute tolerance, this parameter may only be a scalar.
The local error test applied at each integration step is
abs (local error in x(i)) <= ...
rtol * abs (y(i)) + atol(i)
|
"integration method"A string specifying the method of integration to use to solve the ODE system. Valid values are
"adams""non-stiff"No Jacobian used (even if it is available).
"bdf""stiff"Use stiff backward differentiation formula (BDF) method. If a
function to compute the Jacobian is not supplied, lsode will
compute a finite difference approximation of the Jacobian matrix.
"initial step size"The step size to be attempted on the first step (default is determined automatically).
"maximum order"Restrict the maximum order of the solution method. If using the Adams method, this option must be between 1 and 12. Otherwise, it must be between 1 and 5, inclusive.
"maximum step size"Setting the maximum stepsize will avoid passing over very large regions (default is not specified).
"minimum step size"The minimum absolute step size allowed (default is 0).
"step limit"Maximum number of steps allowed (default is 100000).
Here is an example of solving a set of three differential equations using
lsode. Given the function
## oregonator differential equation
function xdot = f (x, t)
xdot = zeros (3,1);
xdot(1) = 77.27 * (x(2) - x(1)*x(2) + x(1) \
- 8.375e-06*x(1)^2);
xdot(2) = (x(3) - x(1)*x(2) - x(2)) / 77.27;
xdot(3) = 0.161*(x(1) - x(3));
endfunction
|
and the initial condition x0 = [ 4; 1.1; 4 ], the set of
equations can be integrated using the command
t = linspace (0, 500, 1000);
y = lsode ("f", x0, t);
|
If you try this, you will see that the value of the result changes dramatically between t = 0 and 5, and again around t = 305. A more efficient set of output points might be
t = [0, logspace(-1, log10(303), 150), \
logspace(log10(304), log10(500), 150)];
|
See Alan C. Hindmarsh, ODEPACK, A Systematized Collection of ODE
Solvers, in Scientific Computing, R. S. Stepleman, editor, (1983) for
more information about the inner workings of lsode.
An m-file for the differential equation used above is included with the Octave distribution in the examples directory under the name ‘oregonator.m’.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The function daspk can be used to solve DAEs of the form
0 = f (x-dot, x, t), x(t=0) = x_0, x-dot(t=0) = x-dot_0 |
where x-dot is the derivative of x. The equation is solved using Petzold’s DAE solver DASPK.
Solve the set of differential-algebraic equations
0 = f (x, xdot, t) |
with
x(t_0) = x_0, xdot(t_0) = xdot_0 |
The solution is returned in the matrices x and xdot, with each row in the result matrices corresponding to one of the elements in the vector t. The first element of t should be t_0 and correspond to the initial state of the system x_0 and its derivative xdot_0, so that the first row of the output x is x_0 and the first row of the output xdot is xdot_0.
The first argument, fcn, is a string, inline, or function handle that names the function f to call to compute the vector of residuals for the set of equations. It must have the form
res = f (x, xdot, t) |
in which x, xdot, and res are vectors, and t is a scalar.
If fcn is a two-element string array or a two-element cell array of strings, inline functions, or function handles, the first element names the function f described above, and the second element names a function to compute the modified Jacobian
df df
jac = -- + c ------
dx d xdot
|
The modified Jacobian function must have the form
jac = j (x, xdot, t, c) |
The second and third arguments to daspk specify the initial
condition of the states and their derivatives, and the fourth argument
specifies a vector of output times at which the solution is desired,
including the time corresponding to the initial condition.
The set of initial states and derivatives are not strictly required to
be consistent. If they are not consistent, you must use the
daspk_options function to provide additional information so
that daspk can compute a consistent starting point.
The fifth argument is optional, and may be used to specify a set of times that the DAE solver should not integrate past. It is useful for avoiding difficulties with singularities and points where there is a discontinuity in the derivative.
After a successful computation, the value of istate will be greater than zero (consistent with the Fortran version of DASPK).
If the computation is not successful, the value of istate will be less than zero and msg will contain additional information.
You can use the function daspk_options to set optional
parameters for daspk.
See also: dassl.
Query or set options for the function daspk.
When called with no arguments, the names of all available options and
their current values are displayed.
Given one argument, return the value of the corresponding option.
When called with two arguments, daspk_options set the option
opt to value val.
Options include
"absolute tolerance"Absolute tolerance. May be either vector or scalar. If a vector, it must match the dimension of the state vector, and the relative tolerance must also be a vector of the same length.
"relative tolerance"Relative tolerance. May be either vector or scalar. If a vector, it must match the dimension of the state vector, and the absolute tolerance must also be a vector of the same length.
The local error test applied at each integration step is
abs (local error in x(i))
<= rtol(i) * abs (Y(i)) + atol(i)
|
"compute consistent initial condition"Denoting the differential variables in the state vector by ‘Y_d’
and the algebraic variables by ‘Y_a’, ddaspk can solve
one of two initialization problems:
In either case, initial values for the given components are input, and initial guesses for the unknown components must also be provided as input. Set this option to 1 to solve the first problem, or 2 to solve the second (the default is 0, so you must provide a set of initial conditions that are consistent).
If this option is set to a nonzero value, you must also set the
"algebraic variables" option to declare which variables in the
problem are algebraic.
"use initial condition heuristics"Set to a nonzero value to use the initial condition heuristics options described below.
"initial condition heuristics"A vector of the following parameters that can be used to control the initial condition calculation.
MXNITMaximum number of Newton iterations (default is 5).
MXNJMaximum number of Jacobian evaluations (default is 6).
MXNHMaximum number of values of the artificial stepsize parameter to be
tried if the "compute consistent initial condition" option has
been set to 1 (default is 5).
Note that the maximum total number of Newton iterations allowed is
MXNIT*MXNJ*MXNH if the "compute consistent initial
condition" option has been set to 1 and MXNIT*MXNJ if it is
set to 2.
LSOFFSet to a nonzero value to disable the linesearch algorithm (default is 0).
STPTOLMinimum scaled step in linesearch algorithm (default is eps^(2/3)).
EPINITSwing factor in the Newton iteration convergence test. The test is
applied to the residual vector, premultiplied by the approximate
Jacobian. For convergence, the weighted RMS norm of this vector
(scaled by the error weights) must be less than EPINIT*EPCON,
where EPCON = 0.33 is the analogous test constant used in the
time steps. The default is EPINIT = 0.01.
"print initial condition info"Set this option to a nonzero value to display detailed information about the initial condition calculation (default is 0).
"exclude algebraic variables from error test"Set to a nonzero value to exclude algebraic variables from the error
test. You must also set the "algebraic variables" option to
declare which variables in the problem are algebraic (default is 0).
"algebraic variables"A vector of the same length as the state vector. A nonzero element indicates that the corresponding element of the state vector is an algebraic variable (i.e., its derivative does not appear explicitly in the equation set.
This option is required by the
compute consistent initial condition" and
"exclude algebraic variables from error test" options.
"enforce inequality constraints"Set to one of the following values to enforce the inequality
constraints specified by the "inequality constraint types"
option (default is 0).
"inequality constraint types"A vector of the same length as the state specifying the type of inequality constraint. Each element of the vector corresponds to an element of the state and should be assigned one of the following codes
Less than zero.
Less than or equal to zero.
Not constrained.
Greater than or equal to zero.
Greater than zero.
This option only has an effect if the
"enforce inequality constraints" option is nonzero.
"initial step size"Differential-algebraic problems may occasionally suffer from severe scaling difficulties on the first step. If you know a great deal about the scaling of your problem, you can help to alleviate this problem by specifying an initial stepsize (default is computed automatically).
"maximum order"Restrict the maximum order of the solution method. This option must be between 1 and 5, inclusive (default is 5).
"maximum step size"Setting the maximum stepsize will avoid passing over very large regions (default is not specified).
Octave also includes DASSL, an earlier version of DASPK, and DASRT, which can be used to solve DAEs with constraints (stopping conditions).
Solve the set of differential-algebraic equations
0 = f (x, xdot, t) |
with
x(t_0) = x_0, xdot(t_0) = xdot_0 |
The solution is returned in the matrices x and xdot, with each row in the result matrices corresponding to one of the elements in the vector t. The first element of t should be t_0 and correspond to the initial state of the system x_0 and its derivative xdot_0, so that the first row of the output x is x_0 and the first row of the output xdot is xdot_0.
The first argument, fcn, is a string, inline, or function handle that names the function f to call to compute the vector of residuals for the set of equations. It must have the form
res = f (x, xdot, t) |
in which x, xdot, and res are vectors, and t is a scalar.
If fcn is a two-element string array or a two-element cell array of strings, inline functions, or function handles, the first element names the function f described above, and the second element names a function to compute the modified Jacobian
df df
jac = -- + c ------
dx d xdot
|
The modified Jacobian function must have the form
jac = j (x, xdot, t, c) |
The second and third arguments to dassl specify the initial
condition of the states and their derivatives, and the fourth argument
specifies a vector of output times at which the solution is desired,
including the time corresponding to the initial condition.
The set of initial states and derivatives are not strictly required to be consistent. In practice, however, DASSL is not very good at determining a consistent set for you, so it is best if you ensure that the initial values result in the function evaluating to zero.
The fifth argument is optional, and may be used to specify a set of times that the DAE solver should not integrate past. It is useful for avoiding difficulties with singularities and points where there is a discontinuity in the derivative.
After a successful computation, the value of istate will be greater than zero (consistent with the Fortran version of DASSL).
If the computation is not successful, the value of istate will be less than zero and msg will contain additional information.
You can use the function dassl_options to set optional
parameters for dassl.
Query or set options for the function dassl.
When called with no arguments, the names of all available options and
their current values are displayed.
Given one argument, return the value of the corresponding option.
When called with two arguments, dassl_options set the option
opt to value val.
Options include
"absolute tolerance"Absolute tolerance. May be either vector or scalar. If a vector, it must match the dimension of the state vector, and the relative tolerance must also be a vector of the same length.
"relative tolerance"Relative tolerance. May be either vector or scalar. If a vector, it must match the dimension of the state vector, and the absolute tolerance must also be a vector of the same length.
The local error test applied at each integration step is
abs (local error in x(i))
<= rtol(i) * abs (Y(i)) + atol(i)
|
"compute consistent initial condition"If nonzero, dassl will attempt to compute a consistent set of initial
conditions. This is generally not reliable, so it is best to provide
a consistent set and leave this option set to zero.
"enforce nonnegativity constraints"If you know that the solutions to your equations will always be non-negative, it may help to set this parameter to a nonzero value. However, it is probably best to try leaving this option set to zero first, and only setting it to a nonzero value if that doesn’t work very well.
"initial step size"Differential-algebraic problems may occasionally suffer from severe scaling difficulties on the first step. If you know a great deal about the scaling of your problem, you can help to alleviate this problem by specifying an initial stepsize.
"maximum order"Restrict the maximum order of the solution method. This option must be between 1 and 5, inclusive.
"maximum step size"Setting the maximum stepsize will avoid passing over very large regions (default is not specified).
"step limit"Maximum number of integration steps to attempt on a single call to the underlying Fortran code.
Solve the set of differential-algebraic equations
0 = f (x, xdot, t) |
with
x(t_0) = x_0, xdot(t_0) = xdot_0 |
with functional stopping criteria (root solving).
The solution is returned in the matrices x and xdot, with each row in the result matrices corresponding to one of the elements in the vector t_out. The first element of t should be t_0 and correspond to the initial state of the system x_0 and its derivative xdot_0, so that the first row of the output x is x_0 and the first row of the output xdot is xdot_0.
The vector t provides an upper limit on the length of the integration. If the stopping condition is met, the vector t_out will be shorter than t, and the final element of t_out will be the point at which the stopping condition was met, and may not correspond to any element of the vector t.
The first argument, fcn, is a string, inline, or function handle that names the function f to call to compute the vector of residuals for the set of equations. It must have the form
res = f (x, xdot, t) |
in which x, xdot, and res are vectors, and t is a scalar.
If fcn is a two-element string array or a two-element cell array of strings, inline functions, or function handles, the first element names the function f described above, and the second element names a function to compute the modified Jacobian
df df
jac = -- + c ------
dx d xdot
|
The modified Jacobian function must have the form
jac = j (x, xdot, t, c) |
The optional second argument names a function that defines the constraint functions whose roots are desired during the integration. This function must have the form
g_out = g (x, t) |
and return a vector of the constraint function values. If the value of any of the constraint functions changes sign, DASRT will attempt to stop the integration at the point of the sign change.
If the name of the constraint function is omitted, dasrt solves
the same problem as daspk or dassl.
Note that because of numerical errors in the constraint functions due to round-off and integration error, DASRT may return false roots, or return the same root at two or more nearly equal values of T. If such false roots are suspected, the user should consider smaller error tolerances or higher precision in the evaluation of the constraint functions.
If a root of some constraint function defines the end of the problem, the input to DASRT should nevertheless allow integration to a point slightly past that root, so that DASRT can locate the root by interpolation.
The third and fourth arguments to dasrt specify the initial
condition of the states and their derivatives, and the fourth argument
specifies a vector of output times at which the solution is desired,
including the time corresponding to the initial condition.
The set of initial states and derivatives are not strictly required to be consistent. In practice, however, DASSL is not very good at determining a consistent set for you, so it is best if you ensure that the initial values result in the function evaluating to zero.
The sixth argument is optional, and may be used to specify a set of times that the DAE solver should not integrate past. It is useful for avoiding difficulties with singularities and points where there is a discontinuity in the derivative.
After a successful computation, the value of istate will be greater than zero (consistent with the Fortran version of DASSL).
If the computation is not successful, the value of istate will be less than zero and msg will contain additional information.
You can use the function dasrt_options to set optional
parameters for dasrt.
See also: dasrt_options, daspk, dasrt, lsode.
Query or set options for the function dasrt.
When called with no arguments, the names of all available options and
their current values are displayed.
Given one argument, return the value of the corresponding option.
When called with two arguments, dasrt_options set the option
opt to value val.
Options include
"absolute tolerance"Absolute tolerance. May be either vector or scalar. If a vector, it must match the dimension of the state vector, and the relative tolerance must also be a vector of the same length.
"relative tolerance"Relative tolerance. May be either vector or scalar. If a vector, it must match the dimension of the state vector, and the absolute tolerance must also be a vector of the same length.
The local error test applied at each integration step is
abs (local error in x(i)) <= ...
rtol(i) * abs (Y(i)) + atol(i)
|
"initial step size"Differential-algebraic problems may occasionally suffer from severe scaling difficulties on the first step. If you know a great deal about the scaling of your problem, you can help to alleviate this problem by specifying an initial stepsize.
"maximum order"Restrict the maximum order of the solution method. This option must be between 1 and 5, inclusive.
"maximum step size"Setting the maximum stepsize will avoid passing over very large regions.
"step limit"Maximum number of integration steps to attempt on a single call to the underlying Fortran code.
See K. E. Brenan, et al., Numerical Solution of Initial-Value Problems in Differential-Algebraic Equations, North-Holland (1989) for more information about the implementation of DASSL.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave comes with support for solving various kinds of optimization problems. Specifically Octave can solve problems in Linear Programming, Quadratic Programming, Nonlinear Programming, and Linear Least Squares Minimization.
| 25.1 Linear Programming | ||
| 25.2 Quadratic Programming | ||
| 25.3 Nonlinear Programming | ||
| 25.4 Linear Least Squares |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave can solve Linear Programming problems using the glpk
function. That is, Octave can solve
min C'*x |
subject to the linear constraints A*x = b where x ≥ 0.
The glpk function also supports variations of this problem.
Solve a linear program using the GNU GLPK library. Given three
arguments, glpk solves the following standard LP:
min C'*x |
subject to
A*x = b x >= 0 |
but may also solve problems of the form
[ min | max ] C'*x |
subject to
A*x [ "=" | "<=" | ">=" ] b x >= LB x <= UB |
Input arguments:
A column array containing the objective function coefficients.
A matrix containing the constraints coefficients.
A column array containing the right-hand side value for each constraint in the constraint matrix.
An array containing the lower bound on each of the variables. If lb is not supplied, the default lower bound for the variables is zero.
An array containing the upper bound on each of the variables. If ub is not supplied, the default upper bound is assumed to be infinite.
An array of characters containing the sense of each constraint in the constraint matrix. Each element of the array may be one of the following values
"F"A free (unbounded) constraint (the constraint is ignored).
"U"An inequality constraint with an upper bound (A(i,:)*x <= b(i)).
"S"An equality constraint (A(i,:)*x = b(i)).
"L"An inequality with a lower bound (A(i,:)*x >= b(i)).
"D"An inequality constraint with both upper and lower bounds
(A(i,:)*x >= -b(i) and (A(i,:)*x <= b(i)).
A column array containing the types of the variables.
"C"A continuous variable.
"I"An integer variable.
If sense is 1, the problem is a minimization. If sense is -1, the problem is a maximization. The default value is 1.
A structure containing the following parameters used to define the behavior of solver. Missing elements in the structure take on default values, so you only need to set the elements that you wish to change from the default.
Integer parameters:
msglev (default: 1)Level of messages output by solver routines:
GLP_MSG_OFF)No output.
GLP_MSG_ERR)Error and warning messages only.
GLP_MSG_ON)Normal output.
GLP_MSG_ALL)Full output (includes informational messages).
scale (default: 16)Scaling option. The values can be combined with the bitwise OR operator and may be the following:
GLP_SF_GM)Geometric mean scaling.
GLP_SF_EQ)Equilibration scaling.
GLP_SF_2N)Round scale factors to power of two.
GLP_SF_SKIP)Skip if problem is well scaled.
Alternatively, a value of 128 (GLP_SF_AUTO) may be also
specified, in which case the routine chooses the scaling options
automatically.
dual (default: 1)Simplex method option:
GLP_PRIMAL)Use two-phase primal simplex.
GLP_DUALP)Use two-phase dual simplex, and if it fails, switch to the primal simplex.
GLP_DUAL)Use two-phase dual simplex.
price (default: 34)Pricing option (for both primal and dual simplex):
GLP_PT_STD)Textbook pricing.
GLP_PT_PSE)Steepest edge pricing.
itlim (default: intmax)Simplex iterations limit. It is decreased by one each time when one simplex iteration has been performed, and reaching zero value signals the solver to stop the search.
outfrq (default: 200)Output frequency, in iterations. This parameter specifies how frequently the solver sends information about the solution to the standard output.
branch (default: 4)Branching technique option (for MIP only):
GLP_BR_FFV)First fractional variable.
GLP_BR_LFV)Last fractional variable.
GLP_BR_MFV)Most fractional variable.
GLP_BR_DTH)Heuristic by Driebeck and Tomlin.
GLP_BR_PCH)Hybrid pseudocost heuristic.
btrack (default: 4)Backtracking technique option (for MIP only):
GLP_BT_DFS)Depth first search.
GLP_BT_BFS)Breadth first search.
GLP_BT_BLB)Best local bound.
GLP_BT_BPH)Best projection heuristic.
presol (default: 1)If this flag is set, the simplex solver uses the built-in LP presolver. Otherwise the LP presolver is not used.
lpsolver (default: 1)Select which solver to use. If the problem is a MIP problem this flag will be ignored.
Revised simplex method.
Interior point method.
rtest (default: 34)Ratio test technique:
GLP_RT_STD)Standard ("textbook").
GLP_RT_HAR)Harris’ two-pass ratio test.
tmlim (default: intmax)Searching time limit, in milliseconds.
outdly (default: 0)Output delay, in seconds. This parameter specifies how long the solver should delay sending information about the solution to the standard output.
save (default: 0)If this parameter is nonzero, save a copy of the problem in CPLEX LP format to the file ‘"outpb.lp"’. There is currently no way to change the name of the output file.
Real parameters:
tolbnd (default: 1e-7)Relative tolerance used to check if the current basic solution is primal feasible. It is not recommended that you change this parameter unless you have a detailed understanding of its purpose.
toldj (default: 1e-7)Absolute tolerance used to check if the current basic solution is dual feasible. It is not recommended that you change this parameter unless you have a detailed understanding of its purpose.
tolpiv (default: 1e-10)Relative tolerance used to choose eligible pivotal elements of the simplex table. It is not recommended that you change this parameter unless you have a detailed understanding of its purpose.
objll (default: -DBL_MAX)Lower limit of the objective function. If the objective function reaches this limit and continues decreasing, the solver stops the search. This parameter is used in the dual simplex method only.
objul (default: +DBL_MAX)Upper limit of the objective function. If the objective function reaches this limit and continues increasing, the solver stops the search. This parameter is used in the dual simplex only.
tolint (default: 1e-5)Relative tolerance used to check if the current basic solution is integer feasible. It is not recommended that you change this parameter unless you have a detailed understanding of its purpose.
tolobj (default: 1e-7)Relative tolerance used to check if the value of the objective function is not better than in the best known integer feasible solution. It is not recommended that you change this parameter unless you have a detailed understanding of its purpose.
Output values:
The optimizer (the value of the decision variables at the optimum).
The optimum value of the objective function.
Error code.
No error.
GLP_EBADB)Invalid basis.
GLP_ESING)Singular matrix.
GLP_ECOND)Ill-conditioned matrix.
GLP_EBOUND)Invalid bounds.
GLP_EFAIL)Solver failed.
GLP_EOBJLL)Objective function lower limit reached.
GLP_EOBJUL)Objective function upper limit reached.
GLP_EITLIM)Iterations limit exhausted.
GLP_ETMLIM)Time limit exhausted.
GLP_ENOPFS)No primal feasible solution.
GLP_ENODFS)No dual feasible solution.
GLP_EROOT)Root LP optimum not provided.
GLP_ESTOP)Search terminated by application.
GLP_EMIPGAP)Relative MIP gap tolerance reached.
GLP_ENOFEAS)No primal/dual feasible solution.
GLP_ENOCVG)No convergence.
GLP_EINSTAB)Numerical instability.
GLP_EDATA)Invalid data.
GLP_ERANGE)Result out of range.
A data structure containing the following fields:
lambdaDual variables.
redcostsReduced Costs.
timeTime (in seconds) used for solving LP/MIP problem.
statusStatus of the optimization.
GLP_UNDEF)Solution status is undefined.
GLP_FEAS)Solution is feasible.
GLP_INFEAS)Solution is infeasible.
GLP_NOFEAS)Problem has no feasible solution.
GLP_OPT)Solution is optimal.
GLP_UNBND)Problem has no unbounded solution.
Example:
c = [10, 6, 4]';
A = [ 1, 1, 1;
10, 4, 5;
2, 2, 6];
b = [100, 600, 300]';
lb = [0, 0, 0]';
ub = [];
ctype = "UUU";
vartype = "CCC";
s = -1;
param.msglev = 1;
param.itlim = 100;
[xmin, fmin, status, extra] = ...
glpk (c, A, b, lb, ub, ctype, vartype, s, param);
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave can also solve Quadratic Programming problems, this is
min 0.5 x'*H*x + x'*q |
subject to
A*x = b
lb <= x <= ub
A_lb <= A_in*x <= A_ub
|
Solve the quadratic program
min 0.5 x'*H*x + x'*q x |
subject to
A*x = b lb <= x <= ub A_lb <= A_in*x <= A_ub |
using a null-space active-set method.
Any bound (A, b, lb, ub, A_lb,
A_ub) may be set to the empty matrix ([]) if not
present. If the initial guess is feasible the algorithm is faster.
An optional structure containing the following parameter(s) used to define the behavior of the solver. Missing elements in the structure take on default values, so you only need to set the elements that you wish to change from the default.
MaxIter (default: 200)Maximum number of iterations.
Structure containing run-time information about the algorithm. The following fields are defined:
solveiterThe number of iterations required to find the solution.
infoAn integer indicating the status of the solution.
The problem is feasible and convex. Global solution found.
The problem is not convex. Local solution found.
The problem is not convex and unbounded.
Maximum number of iterations reached.
The problem is infeasible.
Minimize 1/2*x'*c*x + d'*x subject to x >= 0. c
and d must be real, and c must be symmetric and positive
definite. x0 is an optional initial guess for x.
Outputs:
The minimum attained model value, 1/2*xmin’*c*xmin + d’*xmin
An indicator of convergence. 0 indicates that the iteration count was exceeded, and therefore convergence was not reached; >0 indicates that the algorithm converged. (The algorithm is stable and will converge given enough iterations.)
A structure with two fields:
"algorithm": The algorithm used ("nnls")
"iterations": The number of iterations taken.
Not implemented.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave can also perform general nonlinear minimization using a successive quadratic programming solver.
Solve the nonlinear program
min phi (x) x |
subject to
g(x) = 0 h(x) >= 0 lb <= x <= ub |
using a sequential quadratic programming method.
The first argument is the initial guess for the vector x0.
The second argument is a function handle pointing to the objective function phi. The objective function must accept one vector argument and return a scalar.
The second argument may also be a 2- or 3-element cell array of function handles. The first element should point to the objective function, the second should point to a function that computes the gradient of the objective function, and the third should point to a function that computes the Hessian of the objective function. If the gradient function is not supplied, the gradient is computed by finite differences. If the Hessian function is not supplied, a BFGS update formula is used to approximate the Hessian.
When supplied, the gradient function phi{2} must accept
one vector argument and return a vector. When supplied, the Hessian
function phi{3} must accept one vector argument and
return a matrix.
The third and fourth arguments g and h are function handles pointing to functions that compute the equality constraints and the inequality constraints, respectively. If the problem does not have equality (or inequality) constraints, then use an empty matrix ([]) for g (or h). When supplied, these equality and inequality constraint functions must accept one vector argument and return a vector.
The third and fourth arguments may also be 2-element cell arrays of function handles. The first element should point to the constraint function and the second should point to a function that computes the gradient of the constraint function:
[ d f(x) d f(x) d f(x) ]
transpose ( [ ------ ----- ... ------ ] )
[ dx_1 dx_2 dx_N ]
|
The fifth and sixth arguments, lb and ub, contain lower and upper bounds on x. These must be consistent with the equality and inequality constraints g and h. If the arguments are vectors then x(i) is bound by lb(i) and ub(i). A bound can also be a scalar in which case all elements of x will share the same bound. If only one bound (lb, ub) is specified then the other will default to (-realmax, +realmax).
The seventh argument maxiter specifies the maximum number of iterations. The default value is 100.
The eighth argument tol specifies the tolerance for the
stopping criteria. The default value is sqrt (eps).
The value returned in info may be one of the following:
The algorithm terminated normally.
Either all constraints meet the requested tolerance, or the stepsize,
delta x,
is less than tol * norm (x).
The BFGS update failed.
The maximum number of iterations was reached.
An example of calling sqp:
function r = g (x)
r = [ sumsq(x)-10;
x(2)*x(3)-5*x(4)*x(5);
x(1)^3+x(2)^3+1 ];
endfunction
function obj = phi (x)
obj = exp (prod (x)) - 0.5*(x(1)^3+x(2)^3+1)^2;
endfunction
x0 = [-1.8; 1.7; 1.9; -0.8; -0.8];
[x, obj, info, iter, nf, lambda] = sqp (x0, @phi, @g, [])
x =
-1.71714
1.59571
1.82725
-0.76364
-0.76364
obj = 0.053950
info = 101
iter = 8
nf = 10
lambda =
-0.0401627
0.0379578
-0.0052227
|
See also: qp.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave also supports linear least squares minimization. That is,
Octave can find the parameter b such that the model
y = x*b
fits data (x,y) as well as possible, assuming zero-mean
Gaussian noise. If the noise is assumed to be isotropic the problem
can be solved using the ‘\’ or ‘/’ operators, or the ols
function. In the general case where the noise is assumed to be anisotropic
the gls is needed.
Ordinary least squares estimation for the multivariate model y = x*b + e with mean (e) = 0 and cov (vec (e)) = kron (s, I). where y is a t by p matrix, x is a t by k matrix, b is a k by p matrix, and e is a t by p matrix.
Each row of y and x is an observation and each column a variable.
The return values beta, sigma, and r are defined as follows.
The OLS estimator for b.
beta is calculated directly via inv (x'*x) * x' * y if the
matrix x'*x is of full rank.
Otherwise, beta = pinv (x) * y where
pinv (x) denotes the pseudoinverse of x.
The OLS estimator for the matrix s,
sigma = (y-x*beta)' * (y-x*beta) / (t-rank(x)) |
The matrix of OLS residuals, r = y - x*beta.
Generalized least squares estimation for the multivariate model y = x*b + e with mean (e) = 0 and cov (vec (e)) = (s^2) o, where y is a t by p matrix, x is a t by k matrix, b is a k by p matrix, e is a t by p matrix, and o is a t*p by t*p matrix.
Each row of y and x is an observation and each column a variable. The return values beta, v, and r are defined as follows.
The GLS estimator for b.
The GLS estimator for s^2.
The matrix of GLS residuals, r = y - x*beta.
See also: ols.
Minimize norm (c*x - d) subject to
x >= 0. c and d must be real. x0 is an
optional initial guess for x.
Currently, lsqnonneg
recognizes these options: "MaxIter", "TolX".
For a description of these options, see optimset.
Outputs:
The squared 2-norm of the residual: norm (c*x-d)^2
The residual: d-c*x
An indicator of convergence. 0 indicates that the iteration count was exceeded, and therefore convergence was not reached; >0 indicates that the algorithm converged. (The algorithm is stable and will converge given enough iterations.)
A structure with two fields:
"algorithm": The algorithm used ("nnls")
"iterations": The number of iterations taken.
Not implemented.
Create options struct for optimization functions.
Valid parameters are:
Request verbose display of results from optimizations. Values are:
"off" [default]No display.
"iter"Display intermediate results for every loop iteration.
"final"Display the result of the final loop iteration.
"notify"Display the result of the final loop iteration if the function has failed to converge.
When enabled, display an error if the objective function returns an invalid
value (a complex number, NaN, or Inf). Must be set to "on" or
"off" [default]. Note: the functions fzero and
fminbnd correctly handle Inf values and only complex values or NaN
will cause an error in this case.
When set to "on", the function to be minimized must return a
second argument which is the gradient, or first derivative, of the
function at the point x. If set to "off" [default], the
gradient is computed via finite differences.
When set to "on", the function to be minimized must return a
second argument which is the Jacobian, or first derivative, of the
function at the point x. If set to "off" [default], the
Jacobian is computed via finite differences.
Maximum number of function evaluations before optimization stops. Must be a positive integer.
Maximum number of algorithm iterations before optimization stops. Must be a positive integer.
A user-defined function executed once per algorithm iteration.
Termination criterion for the function output. If the difference in the
calculated objective function between one algorithm iteration and the next
is less than TolFun the optimization stops. Must be a positive
scalar.
Termination criterion for the function input. If the difference in x,
the current search point, between one algorithm iteration and the next is
less than TolX the optimization stops. Must be a positive scalar.
Return a specific option from a structure created by
optimset. If parname is not a field of the options
structure, return default if supplied, otherwise return an
empty matrix.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave has support for various statistical methods. This includes basic descriptive statistics, probability distributions, statistical tests, random number generation, and much more.
The functions that analyze data all assume that multi-dimensional data is arranged in a matrix where each row is an observation, and each column is a variable. Thus, the matrix defined by
a = [ 0.9, 0.7;
0.1, 0.1;
0.5, 0.4 ];
|
contains three observations from a two-dimensional distribution. While this is the default data arrangement, most functions support different arrangements.
It should be noted that the statistics functions don’t test for data containing NaN, NA, or Inf. These values need to be detected and dealt with explicitly. See isnan, isna, isinf, isfinite.
| 26.1 Descriptive Statistics | ||
| 26.2 Basic Statistical Functions | ||
| 26.3 Statistical Plots | ||
| 26.4 Correlation and Regression Analysis | ||
| 26.5 Distributions | ||
| 26.6 Tests | ||
| 26.7 Random Number Generation |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
One principal goal of descriptive statistics is to represent the essence of a large data set concisely. Octave provides the mean, median, and mode functions which all summarize a data set with just a single number corresponding to the central tendency of the data.
Compute the mean of the elements of the vector x.
mean (x) = SUM_i x(i) / N |
If x is a matrix, compute the mean for each column and return them in a row vector.
The optional argument opt selects the type of mean to compute. The following options are recognized:
"a"Compute the (ordinary) arithmetic mean. [default]
"g"Compute the geometric mean.
"h"Compute the harmonic mean.
If the optional argument dim is given, operate along this dimension.
Both dim and opt are optional. If both are supplied, either may appear first.
Compute the median value of the elements of the vector x. If the elements of x are sorted, the median is defined as
x(ceil(N/2)) N odd
median (x) =
(x(N/2) + x((N/2)+1))/2 N even
|
If x is a matrix, compute the median value for each column and return them in a row vector. If the optional dim argument is given, operate along this dimension.
Compute the most frequently occurring value in a dataset (mode).
mode determines the frequency of values along the first non-singleton
dimension and returns the value with the highest frequency. If two, or
more, values have the same frequency mode returns the smallest.
If the optional argument dim is given, operate along this dimension.
The return variable f is the number of occurrences of the mode in in the dataset. The cell array c contains all of the elements with the maximum frequency.
Using just one number, such as the mean, to represent an entire data set may not give an accurate picture of the data. One way to characterize the fit is to measure the dispersion of the data. Octave provides several functions for measuring dispersion.
Return the range, i.e., the difference between the maximum and the minimum of the input data. If x is a vector, the range is calculated over the elements of x. If x is a matrix, the range is calculated over each column of x.
If the optional argument dim is given, operate along this dimension.
The range is a quickly computed measure of the dispersion of a data set, but
is less accurate than iqr if there are outlying data points.
Return the interquartile range, i.e., the difference between the upper and lower quartile of the input data. If x is a matrix, do the above for first non-singleton dimension of x.
If the optional argument dim is given, operate along this dimension.
As a measure of dispersion, the interquartile range is less affected by
outliers than either range or std.
Compute the mean square of the elements of the vector x.
std (x) = 1/N SUM_i x(i)^2 |
For matrix arguments, return a row vector containing the mean square of each column.
If the optional argument dim is given, operate along this dimension.
Compute the standard deviation of the elements of the vector x.
std (x) = sqrt ( 1/(N-1) SUM_i (x(i) - mean(x))^2 ) |
where N is the number of elements.
If x is a matrix, compute the standard deviation for each column and return them in a row vector.
The argument opt determines the type of normalization to use. Valid values are
normalize with N-1, provides the square root of the best unbiased estimator of the variance [default]
normalize with N, this provides the square root of the second moment around the mean
If the optional argument dim is given, operate along this dimension.
In addition to knowing the size of a dispersion it is useful to know the shape of the data set. For example, are data points massed to the left or right of the mean? Octave provides several common measures to describe the shape of the data set. Octave can also calculate moments allowing arbitrary shape measures to be developed.
Compute the variance of the elements of the vector x.
var (x) = 1/(N-1) SUM_i (x(i) - mean(x))^2 |
If x is a matrix, compute the variance for each column and return them in a row vector.
The argument opt determines the type of normalization to use. Valid values are
normalize with N-1, provides the best unbiased estimator of the variance [default]
normalizes with N, this provides the second moment around the mean
If N==1 the value of opt is ignored and normalization by N is used.
If the optional argument dim is given, operate along this dimension.
Compute the sample skewness of the elements of x:
mean ((x - mean (x)).^3)
skewness (X) = ------------------------.
std (x).^3
|
The optional argument flag controls which normalization is used. If flag is equal to 1 (default value, used when flag is omitted or empty), return the sample skewness as defined above. If flag is equal to 0, return the adjusted skewness coefficient instead:
sqrt (N*(N-1)) mean ((x - mean (x)).^3)
skewness (X, 0) = -------------- * ------------------------.
(N - 2) std (x).^3
|
The adjusted skewness coefficient is obtained by replacing the sample second and third central moments by their bias-corrected versions.
If x is a matrix, or more generally a multi-dimensional array, return the skewness along the first non-singleton dimension. If the optional dim argument is given, operate along this dimension.
Compute the sample kurtosis of the elements of x:
mean ((x - mean (x)).^4)
k1 = ------------------------
std (x).^4
|
The optional argument flag controls which normalization is used. If flag is equal to 1 (default value, used when flag is omitted or empty), return the sample kurtosis as defined above. If flag is equal to 0, return the "bias-corrected" kurtosis coefficient instead:
N - 1
k0 = 3 + -------------- * ((N + 1) * k1 - 3 * (N - 1))
(N - 2)(N - 3)
|
The bias-corrected kurtosis coefficient is obtained by replacing the sample second and fourth central moments by their unbiased versions. It is an unbiased estimate of the population kurtosis for normal populations.
If x is a matrix, or more generally a multi-dimensional array, return the kurtosis along the first non-singleton dimension. If the optional dim argument is given, operate along this dimension.
Compute the p-th central moment of the vector x.
1/N SUM_i (x(i) - mean(x))^p |
If x is a matrix, return the row vector containing the p-th central moment of each column.
The optional string type specifies the type of moment to be computed. Valid options are:
"c"Central Moment (default).
"a""ac"Absolute Central Moment. The moment about the mean ignoring sign defined as
1/N SUM_i (abs (x(i) - mean(x)))^p |
"r"Raw Moment. The moment about zero defined as
moment (x) = 1/N SUM_i x(i)^p |
"ar"Absolute Raw Moment. The moment about zero ignoring sign defined as
1/N SUM_i ( abs (x(i)) )^p |
If the optional argument dim is given, operate along this dimension.
If both type and dim are given they may appear in any order.
For a sample, x, calculate the quantiles, q, corresponding to the cumulative probability values in p. All non-numeric values (NaNs) of x are ignored.
If x is a matrix, compute the quantiles for each column and return them in a matrix, such that the i-th row of q contains the p(i)th quantiles of each column of x.
If p is unspecified, return the quantiles for
[0.00 0.25 0.50 0.75 1.00].
The optional argument dim determines the dimension along which
the quantiles are calculated. If dim is omitted, and x is
a vector or matrix, it defaults to 1 (column-wise quantiles). If
x is an N-D array, dim defaults to the first non-singleton
dimension.
The methods available to calculate sample quantiles are the nine methods used by R (http://www.r-project.org/). The default value is METHOD = 5.
Discontinuous sample quantile methods 1, 2, and 3
Continuous sample quantile methods 4 through 9, where p(k) is the linear interpolation function respecting each methods’ representative cdf.
Hyndman and Fan (1996) recommend method 8. Maxima, S, and R (versions prior to 2.0.0) use 7 as their default. Minitab and SPSS use method 6. MATLAB uses method 5.
References:
Examples:
x = randi (1000, [10, 1]); # Create empirical data in range 1-1000 q = quantile (x, [0, 1]); # Return minimum, maximum of distribution q = quantile (x, [0.25 0.5 0.75]); # Return quartiles of distribution |
See also: prctile.
For a sample x, compute the quantiles, q, corresponding to the cumulative probability values, p, in percent. All non-numeric values (NaNs) of x are ignored.
If x is a matrix, compute the percentiles for each column and return them in a matrix, such that the i-th row of y contains the p(i)th percentiles of each column of x.
If p is unspecified, return the quantiles for [0 25 50 75 100].
The optional argument dim determines the dimension along which
the percentiles are calculated. If dim is omitted, and x is
a vector or matrix, it defaults to 1 (column-wise quantiles). When
x is an N-D array, dim defaults to the first non-singleton
dimension.
See also: quantile.
A summary view of a data set can be generated quickly with the
statistics function.
Return a vector with the minimum, first quartile, median, third quartile, maximum, mean, standard deviation, skewness, and kurtosis of the elements of the vector x.
If x is a matrix, calculate statistics over the first non-singleton dimension. If the optional argument dim is given, operate along this dimension.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave supports various helpful statistical functions. Many are useful as initial steps to prepare a data set for further analysis. Others provide different measures from those of the basic descriptive statistics.
If x is a vector, subtract its mean. If x is a matrix, do the above for each column. If the optional argument dim is given, operate along this dimension.
See also: zscore.
If x is a vector, subtract its mean and divide by its standard
deviation. If the standard deviation is zero, divide by 1 instead.
The optional parameter opt determines the normalization to use
when computing the standard deviation and is the same as the
corresponding parameter for std.
If x is a matrix, do the above along the first non-singleton dimension. If the third optional argument dim is given, operate along this dimension.
The mean and standard deviation along dim are given in mu and sigma respectively.
Produce histogram counts.
When x is a vector, the function counts the number of elements of
x that fall in the histogram bins defined by edges. This must be
a vector of monotonically increasing values that define the edges of the
histogram bins. n(k) contains the number of elements in
x for which edges(k) <= x < edges(k+1).
The final element of n contains the number of elements of x
exactly equal to the last element of edges.
When x is an N-dimensional array, the computation is carried out along dimension dim. If not specified dim defaults to the first non-singleton dimension.
When a second output argument is requested an index matrix is also returned. The idx matrix has the same size as x. Each element of idx contains the index of the histogram bin in which the corresponding element of x was counted.
See also: hist.
Compute the binomial coefficient or all combinations of a set of items.
If n is a scalar then calculate the binomial coefficient of n and k which is defined as
/ \ | n | n (n-1) (n-2) … (n-k+1) n! | | = ------------------------- = --------- | k | k! k! (n-k)! \ / |
This is the number of combinations of n items taken in groups of size k.
If the first argument is a vector, set, then generate all
combinations of the elements of set, taken k at a time, with
one row per combination. The result c has k columns and
nchoosek (length (set), k) rows.
For example:
How many ways can three items be grouped into pairs?
nchoosek (3, 2) ⇒ 3 |
What are the possible pairs?
nchoosek (1:3, 2)
⇒ 1 2
1 3
2 3
|
nchoosek works only for non-negative, integer arguments. Use
bincoeff for non-integer and negative scalar arguments, or for
computing many binomial coefficients at once with vector inputs
for n or k.
Generate all permutations of v, one row per permutation. The
result has size factorial (n) * n, where n
is the length of v.
As an example, perms ([1, 2, 3]) returns the matrix
1 2 3 2 1 3 1 3 2 2 3 1 3 1 2 3 2 1 |
Return the ranks of x along the first non-singleton dimension adjusted for ties. If the optional argument dim is given, operate along this dimension.
Count the upward runs along the first non-singleton dimension of x of length 1, 2, …, n-1 and greater than or equal to n.
If the optional argument dim is given then operate along this dimension.
Find the lengths of all sequences of common values. Return the vector of lengths and the value that was repeated.
runlength ([2, 2, 0, 4, 4, 4, 0, 1, 1, 1, 1]) ⇒ [2, 1, 3, 1, 4] |
For each component of p, return the probit (the quantile of the standard normal distribution) of p.
For each component of p, return the logit of p defined as
logit (p) = log (p / (1-p)) |
See also: logistic_cdf.
Return the complementary log-log function of x, defined as
cloglog (x) = - log (- log (x)) |
Return the Mahalanobis’ D-square distance between the multivariate samples x and y, which must have the same number of components (columns), but may have a different number of observations (rows).
Create a contingency table t from data vectors. The l_x and l_y vectors are the corresponding levels.
Currently, only 1- and 2-dimensional tables are supported.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave can create Quantile Plots (QQ-Plots), and Probability Plots (PP-Plots). These are simple graphical tests for determining if a data set comes from a certain distribution.
Note that Octave can also show histograms of data
using the hist function as described in
Two-Dimensional Plots.
Perform a QQ-plot (quantile plot).
If F is the CDF of the distribution dist with parameters params and G its inverse, and x a sample vector of length n, the QQ-plot graphs ordinate s(i) = i-th largest element of x versus abscissa q(if) = G((i - 0.5)/n).
If the sample comes from F, except for a transformation of location and scale, the pairs will approximately follow a straight line.
If the second argument is a vector y the empirical CDF of y is used as dist.
The default for dist is the standard normal distribution. The optional argument params contains a list of parameters of dist. For example, for a quantile plot of the uniform distribution on [2,4] and x, use
qqplot (x, "unif", 2, 4) |
dist can be any string for which a function distinv or dist_inv exists that calculates the inverse CDF of distribution dist.
If no output arguments are given, the data are plotted directly.
Perform a PP-plot (probability plot).
If F is the CDF of the distribution dist with parameters params and x a sample vector of length n, the PP-plot graphs ordinate y(i) = F (i-th largest element of x) versus abscissa p(i) = (i - 0.5)/n. If the sample comes from F, the pairs will approximately follow a straight line.
The default for dist is the standard normal distribution. The optional argument params contains a list of parameters of dist. For example, for a probability plot of the uniform distribution on [2,4] and x, use
ppplot (x, "uniform", 2, 4) |
dist can be any string for which a function dist_cdf that calculates the CDF of distribution dist exists.
If no output arguments are given, the data are plotted directly.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Compute the covariance matrix.
If each row of x and y is an observation, and each column is
a variable, then the (i, j)-th entry of
cov (x, y) is the covariance between the i-th
variable in x and the j-th variable in y.
cov (x) = 1/N-1 * SUM_i (x(i) - mean(x)) * (y(i) - mean(y)) |
If called with one argument, compute cov (x, x), the
covariance between the columns of x.
The argument opt determines the type of normalization to use. Valid values are
normalize with N-1, provides the best unbiased estimator of the covariance [default]
normalize with N, this provides the second moment around the mean
MATLAB compatibility: Octave always computes the covariance matrix.
For two inputs, however, MATLAB will calculate
cov (x(:), y(:)) whenever the number of elements in
x and y are equal. This will result in a scalar rather than
a matrix output. Code relying on this odd definition will need to be
changed when running in Octave.
See also: corr.
Compute matrix of correlation coefficients.
If each row of x and y is an observation and each column is
a variable, then the (i, j)-th entry of
corr (x, y) is the correlation between the
i-th variable in x and the j-th variable in y.
corr (x,y) = cov (x,y) / (std (x) * std (y)) |
If called with one argument, compute corr (x, x),
the correlation between the columns of x.
See also: cov.
Compute Spearman’s rank correlation coefficient rho.
For two data vectors x and y, Spearman’s rho is the correlation coefficient of the ranks of x and y.
If x and y are drawn from independent distributions,
rho has zero mean and variance 1 / (n - 1), and is
asymptotically normally distributed.
spearman (x) is equivalent to spearman (x,
x).
Compute Kendall’s tau.
For two data vectors x, y of common length n, Kendall’s tau is the correlation of the signs of all rank differences of x and y; i.e., if both x and y have distinct entries, then
1
tau = ------- SUM sign (q(i) - q(j)) * sign (r(i) - r(j))
n (n-1) i,j
|
in which the q(i) and r(i) are the ranks of x and y, respectively.
If x and y are drawn from independent distributions,
Kendall’s tau is asymptotically normal with mean 0 and variance
(2 * (2n+5)) / (9 * n * (n-1)).
kendall (x) is equivalent to kendall (x,
x).
Perform ordinal logistic regression.
Suppose y takes values in k ordered categories, and let
gamma_i (x) be the cumulative probability that y
falls in one of the first i categories given the covariate
x. Then
[theta, beta] = logistic_regression (y, x) |
fits the model
logit (gamma_i (x)) = theta_i - beta' * x, i = 1 … k-1 |
The number of ordinal categories, k, is taken to be the number
of distinct values of round (y). If k equals 2,
y is binary and the model is ordinary logistic regression. The
matrix x is assumed to have full column rank.
Given y only, theta = logistic_regression (y)
fits the model with baseline logit odds only.
The full form is
[theta, beta, dev, dl, d2l, gamma] = logistic_regression (y, x, print, theta, beta) |
in which all output arguments and all input arguments except y are optional.
Setting print to 1 requests summary information about the fitted model to be displayed. Setting print to 2 requests information about convergence at each iteration. Other values request no information to be displayed. The input arguments theta and beta give initial estimates for theta and beta.
The returned value dev holds minus twice the log-likelihood.
The returned values dl and d2l are the vector of first and the matrix of second derivatives of the log-likelihood with respect to theta and beta.
p holds estimates for the conditional distribution of y given x.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave has functions for computing the Probability Density Function (PDF), the Cumulative Distribution function (CDF), and the quantile (the inverse of the CDF) for a large number of distributions.
The following table summarizes the supported distributions (in alphabetical order).
| Distribution | CDF | Quantile | |
|---|---|---|---|
| Beta Distribution | betapdf | betacdf | betainv |
| Binomial Distribution | binopdf | binocdf | binoinv |
| Cauchy Distribution | cauchy_pdf | cauchy_cdf | cauchy_inv |
| Chi-Square Distribution | chi2pdf | chi2cdf | chi2inv |
| Univariate Discrete Distribution | discrete_pdf | discrete_cdf | discrete_inv |
| Empirical Distribution | empirical_pdf | empirical_cdf | empirical_inv |
| Exponential Distribution | exppdf | expcdf | expinv |
| F Distribution | fpdf | fcdf | finv |
| Gamma Distribution | gampdf | gamcdf | gaminv |
| Geometric Distribution | geopdf | geocdf | geoinv |
| Hypergeometric Distribution | hygepdf | hygecdf | hygeinv |
| Kolmogorov Smirnov Distribution | Not Available | kolmogorov_smirnov_cdf | Not Available |
| Laplace Distribution | laplace_pdf | laplace_cdf | laplace_inv |
| Logistic Distribution | logistic_pdf | logistic_cdf | logistic_inv |
| Log-Normal Distribution | lognpdf | logncdf | logninv |
| Univariate Normal Distribution | normpdf | normcdf | norminv |
| Pascal Distribution | nbinpdf | nbincdf | nbininv |
| Poisson Distribution | poisspdf | poisscdf | poissinv |
| Standard Normal Distribution | stdnormal_pdf | stdnormal_cdf | stdnormal_inv |
| t (Student) Distribution | tpdf | tcdf | tinv |
| Univariate Discrete Distribution | unidpdf | unidcdf | unidinv |
| Uniform Distribution | unifpdf | unifcdf | unifinv |
| Weibull Distribution | wblpdf | wblcdf | wblinv |
For each element of x, compute the probability density function (PDF) at x of the Beta distribution with parameters a and b.
For each element of x, compute the cumulative distribution function (CDF) at x of the Beta distribution with parameters a and b.
For each element of x, compute the quantile (the inverse of the CDF) at x of the Beta distribution with parameters a and b.
For each element of x, compute the probability density function (PDF) at x of the binomial distribution with parameters n and p, where n is the number of trials and p is the probability of success.
For each element of x, compute the cumulative distribution function (CDF) at x of the binomial distribution with parameters n and p, where n is the number of trials and p is the probability of success.
For each element of x, compute the quantile (the inverse of the CDF) at x of the binomial distribution with parameters n and p, where n is the number of trials and p is the probability of success.
For each element of x, compute the probability density function (PDF) at x of the Cauchy distribution with location parameter location and scale parameter scale > 0. Default values are location = 0, scale = 1.
For each element of x, compute the cumulative distribution function (CDF) at x of the Cauchy distribution with location parameter location and scale parameter scale. Default values are location = 0, scale = 1.
For each element of x, compute the quantile (the inverse of the CDF) at x of the Cauchy distribution with location parameter location and scale parameter scale. Default values are location = 0, scale = 1.
For each element of x, compute the probability density function (PDF) at x of the chi-square distribution with n degrees of freedom.
For each element of x, compute the cumulative distribution function (CDF) at x of the chi-square distribution with n degrees of freedom.
For each element of x, compute the quantile (the inverse of the CDF) at x of the chi-square distribution with n degrees of freedom.
For each element of x, compute the probability density function (PDF) at x of a univariate discrete distribution which assumes the values in v with probabilities p.
For each element of x, compute the cumulative distribution function (CDF) at x of a univariate discrete distribution which assumes the values in v with probabilities p.
For each element of x, compute the quantile (the inverse of the CDF) at x of the univariate distribution which assumes the values in v with probabilities p.
For each element of x, compute the probability density function (PDF) at x of the empirical distribution obtained from the univariate sample data.
For each element of x, compute the cumulative distribution function (CDF) at x of the empirical distribution obtained from the univariate sample data.
For each element of x, compute the quantile (the inverse of the CDF) at x of the empirical distribution obtained from the univariate sample data.
For each element of x, compute the probability density function (PDF) at x of the exponential distribution with mean lambda.
For each element of x, compute the cumulative distribution function (CDF) at x of the exponential distribution with mean lambda.
The arguments can be of common size or scalars.
For each element of x, compute the quantile (the inverse of the CDF) at x of the exponential distribution with mean lambda.
For each element of x, compute the probability density function (PDF) at x of the F distribution with m and n degrees of freedom.
For each element of x, compute the cumulative distribution function (CDF) at x of the F distribution with m and n degrees of freedom.
For each element of x, compute the quantile (the inverse of the CDF) at x of the F distribution with m and n degrees of freedom.
For each element of x, return the probability density function (PDF) at x of the Gamma distribution with shape parameter a and scale b.
For each element of x, compute the cumulative distribution function (CDF) at x of the Gamma distribution with shape parameter a and scale b.
For each element of x, compute the quantile (the inverse of the CDF) at x of the Gamma distribution with shape parameter a and scale b.
For each element of x, compute the probability density function (PDF) at x of the geometric distribution with parameter p.
The geometric distribution models the number of failures (x-1) of a Bernoulli trial with probability p before the first success (x).
For each element of x, compute the cumulative distribution function (CDF) at x of the geometric distribution with parameter p.
The geometric distribution models the number of failures (x-1) of a Bernoulli trial with probability p before the first success (x).
For each element of x, compute the quantile (the inverse of the CDF) at x of the geometric distribution with parameter p.
The geometric distribution models the number of failures (x-1) of a Bernoulli trial with probability p before the first success (x).
Compute the probability density function (PDF) at x of the hypergeometric distribution with parameters t, m, and n. This is the probability of obtaining x marked items when randomly drawing a sample of size n without replacement from a population of total size t containing m marked items.
The parameters t, m, and n must be positive integers with m and n not greater than t.
Compute the cumulative distribution function (CDF) at x of the hypergeometric distribution with parameters t, m, and n. This is the probability of obtaining not more than x marked items when randomly drawing a sample of size n without replacement from a population of total size t containing m marked items.
The parameters t, m, and n must be positive integers with m and n not greater than t.
For each element of x, compute the quantile (the inverse of the CDF) at x of the hypergeometric distribution with parameters t, m, and n. This is the probability of obtaining x marked items when randomly drawing a sample of size n without replacement from a population of total size t containing m marked items.
The parameters t, m, and n must be positive integers with m and n not greater than t.
Return the cumulative distribution function (CDF) at x of the Kolmogorov-Smirnov distribution,
Inf
Q(x) = SUM (-1)^k exp (-2 k^2 x^2)
k = -Inf
|
for x > 0.
The optional parameter tol specifies the precision up to which
the series should be evaluated; the default is tol = eps.
For each element of x, compute the probability density function (PDF) at x of the Laplace distribution.
For each element of x, compute the cumulative distribution function (CDF) at x of the Laplace distribution.
For each element of x, compute the quantile (the inverse of the CDF) at x of the Laplace distribution.
For each element of x, compute the PDF at x of the logistic distribution.
For each element of x, compute the cumulative distribution function (CDF) at x of the logistic distribution.
For each element of x, compute the quantile (the inverse of the CDF) at x of the logistic distribution.
For each element of x, compute the probability density function (PDF) at x of the lognormal distribution with parameters mu and sigma. If a random variable follows this distribution, its logarithm is normally distributed with mean mu and standard deviation sigma.
Default values are mu = 0, sigma = 1.
For each element of x, compute the cumulative distribution function (CDF) at x of the lognormal distribution with parameters mu and sigma. If a random variable follows this distribution, its logarithm is normally distributed with mean mu and standard deviation sigma.
Default values are mu = 0, sigma = 1.
For each element of x, compute the quantile (the inverse of the CDF) at x of the lognormal distribution with parameters mu and sigma. If a random variable follows this distribution, its logarithm is normally distributed with mean mu and standard deviation sigma.
Default values are mu = 0, sigma = 1.
For each element of x, compute the probability density function (PDF) at x of the negative binomial distribution with parameters n and p.
When n is integer this is the Pascal distribution. When n is extended to real numbers this is the Polya distribution.
The number of failures in a Bernoulli experiment with success probability p before the n-th success follows this distribution.
For each element of x, compute the cumulative distribution function (CDF) at x of the negative binomial distribution with parameters n and p.
When n is integer this is the Pascal distribution. When n is extended to real numbers this is the Polya distribution.
The number of failures in a Bernoulli experiment with success probability p before the n-th success follows this distribution.
For each element of x, compute the quantile (the inverse of the CDF) at x of the negative binomial distribution with parameters n and p.
When n is integer this is the Pascal distribution. When n is extended to real numbers this is the Polya distribution.
The number of failures in a Bernoulli experiment with success probability p before the n-th success follows this distribution.
For each element of x, compute the probability density function (PDF) at x of the normal distribution with mean mu and standard deviation sigma.
Default values are mu = 0, sigma = 1.
For each element of x, compute the cumulative distribution function (CDF) at x of the normal distribution with mean mu and standard deviation sigma.
Default values are mu = 0, sigma = 1.
For each element of x, compute the quantile (the inverse of the CDF) at x of the normal distribution with mean mu and standard deviation sigma.
Default values are mu = 0, sigma = 1.
For each element of x, compute the probability density function (PDF) at x of the Poisson distribution with parameter lambda.
For each element of x, compute the cumulative distribution function (CDF) at x of the Poisson distribution with parameter lambda.
For each element of x, compute the quantile (the inverse of the CDF) at x of the Poisson distribution with parameter lambda.
For each element of x, compute the probability density function (PDF) at x of the standard normal distribution (mean = 0, standard deviation = 1).
For each element of x, compute the cumulative distribution function (CDF) at x of the standard normal distribution (mean = 0, standard deviation = 1).
For each element of x, compute the quantile (the inverse of the CDF) at x of the standard normal distribution (mean = 0, standard deviation = 1).
For each element of x, compute the probability density function (PDF) at x of the t (Student) distribution with n degrees of freedom.
For each element of x, compute the cumulative distribution function (CDF) at x of the t (Student) distribution with n degrees of freedom, i.e., PROB (t(n) ≤ x).
For each element of x, compute the quantile (the inverse of the CDF) at x of the t (Student) distribution with n degrees of freedom. This function is analogous to looking in a table for the t-value of a single-tailed distribution.
For each element of x, compute the probability density function (PDF) at x of a discrete uniform distribution which assumes the integer values 1–n with equal probability.
Warning: The underlying implementation uses the double class and
will only be accurate for n ≤ bitmax
(2^53 - 1 on IEEE-754 compatible systems).
For each element of x, compute the cumulative distribution function (CDF) at x of a discrete uniform distribution which assumes the integer values 1–n with equal probability.
For each element of x, compute the quantile (the inverse of the CDF) at x of the discrete uniform distribution which assumes the integer values 1–n with equal probability.
For each element of x, compute the probability density function (PDF) at x of the uniform distribution on the interval [a, b].
Default values are a = 0, b = 1.
For each element of x, compute the cumulative distribution function (CDF) at x of the uniform distribution on the interval [a, b].
Default values are a = 0, b = 1.
For each element of x, compute the quantile (the inverse of the CDF) at x of the uniform distribution on the interval [a, b].
Default values are a = 0, b = 1.
Compute the probability density function (PDF) at x of the Weibull distribution with scale parameter scale and shape parameter shape which is given by
shape * scale^(-shape) * x^(shape-1) * exp (-(x/scale)^shape) |
for x ≥ 0.
Default values are scale = 1, shape = 1.
Compute the cumulative distribution function (CDF) at x of the Weibull distribution with scale parameter scale and shape parameter shape, which is
1 - exp (-(x/scale)^shape) |
for x ≥ 0.
Default values are scale = 1, shape = 1.
Compute the quantile (the inverse of the CDF) at x of the Weibull distribution with scale parameter scale and shape parameter shape.
Default values are scale = 1, shape = 1.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave can perform many different statistical tests. The following table summarizes the available tests.
| Hypothesis | Test Functions |
|---|---|
| Equal mean values | anova, hotelling_test2, t_test_2,
welch_test, wilcoxon_test, z_test_2 |
| Equal medians | kruskal_wallis_test, sign_test |
| Equal variances | bartlett_test, manova, var_test |
| Equal distributions | chisquare_test_homogeneity, kolmogorov_smirnov_test_2,
u_test |
| Equal marginal frequencies | mcnemar_test |
| Equal success probabilities | prop_test_2 |
| Independent observations | chisquare_test_independence, run_test |
| Uncorrelated observations | cor_test |
| Given mean value | hotelling_test, t_test, z_test |
| Observations from given distribution | kolmogorov_smirnov_test |
| Regression | f_test_regression, t_test_regression |
The tests return a p-value that describes the outcome of the test. Assuming that the test hypothesis is true, the p-value is the probability of obtaining a worse result than the observed one. So large p-values corresponds to a successful test. Usually a test hypothesis is accepted if the p-value exceeds 0.05.
Perform a one-way analysis of variance (ANOVA). The goal is to test whether the population means of data taken from k different groups are all equal.
Data may be given in a single vector y with groups specified by a corresponding vector of group labels g (e.g., numbers from 1 to k). This is the general form which does not impose any restriction on the number of data in each group or the group labels.
If y is a matrix and g is omitted, each column of y is treated as a group. This form is only appropriate for balanced ANOVA in which the numbers of samples from each group are all equal.
Under the null of constant means, the statistic f follows an F distribution with df_b and df_w degrees of freedom.
The p-value (1 minus the CDF of this distribution at f) is returned in pval.
If no output argument is given, the standard one-way ANOVA table is printed.
Perform a Bartlett test for the homogeneity of variances in the data vectors x1, x2, …, xk, where k > 1.
Under the null of equal variances, the test statistic chisq approximately follows a chi-square distribution with df degrees of freedom.
The p-value (1 minus the CDF of this distribution at chisq) is returned in pval.
If no output argument is given, the p-value is displayed.
Given two samples x and y, perform a chisquare test for homogeneity of the null hypothesis that x and y come from the same distribution, based on the partition induced by the (strictly increasing) entries of c.
For large samples, the test statistic chisq approximately follows a
chisquare distribution with df = length (c)
degrees of freedom.
The p-value (1 minus the CDF of this distribution at chisq) is returned in pval.
If no output argument is given, the p-value is displayed.
Perform a chi-square test for independence based on the contingency table x. Under the null hypothesis of independence, chisq approximately has a chi-square distribution with df degrees of freedom.
The p-value (1 minus the CDF of this distribution at chisq) of the test is returned in pval.
If no output argument is given, the p-value is displayed.
Test whether two samples x and y come from uncorrelated populations.
The optional argument string alt describes the alternative
hypothesis, and can be "!=" or "<>" (non-zero),
">" (greater than 0), or "<" (less than 0). The
default is the two-sided case.
The optional argument string method specifies which
correlation coefficient to use for testing. If method is
"pearson" (default), the (usual) Pearson’s product moment
correlation coefficient is used. In this case, the data should come
from a bivariate normal distribution. Otherwise, the other two
methods offer nonparametric alternatives. If method is
"kendall", then Kendall’s rank correlation tau is used. If
method is "spearman", then Spearman’s rank correlation
rho is used. Only the first character is necessary.
The output is a structure with the following elements:
The p-value of the test.
The value of the test statistic.
The distribution of the test statistic.
The parameters of the null distribution of the test statistic.
The alternative hypothesis.
The method used for testing.
If no output argument is given, the p-value is displayed.
Perform an F test for the null hypothesis rr * b = r in a classical normal regression model y = X * b + e.
Under the null, the test statistic f follows an F distribution with df_num and df_den degrees of freedom.
The p-value (1 minus the CDF of this distribution at f) is returned in pval.
If not given explicitly, r = 0.
If no output argument is given, the p-value is displayed.
For a sample x from a multivariate normal distribution with unknown
mean and covariance matrix, test the null hypothesis that mean
(x) == m.
Hotelling’s T^2 is returned in tsq. Under the null, (n-p) T^2 / (p(n-1)) has an F distribution with p and n-p degrees of freedom, where n and p are the numbers of samples and variables, respectively.
The p-value of the test is returned in pval.
If no output argument is given, the p-value of the test is displayed.
For two samples x from multivariate normal distributions with
the same number of variables (columns), unknown means and unknown
equal covariance matrices, test the null hypothesis mean
(x) == mean (y).
Hotelling’s two-sample T^2 is returned in tsq. Under the null,
(n_x+n_y-p-1) T^2 / (p(n_x+n_y-2)) |
has an F distribution with p and n_x+n_y-p-1 degrees of freedom, where n_x and n_y are the sample sizes and p is the number of variables.
The p-value of the test is returned in pval.
If no output argument is given, the p-value of the test is displayed.
Perform a Kolmogorov-Smirnov test of the null hypothesis that the sample x comes from the (continuous) distribution dist. I.e., if F and G are the CDFs corresponding to the sample and dist, respectively, then the null is that F == G.
The optional argument params contains a list of parameters of dist. For example, to test whether a sample x comes from a uniform distribution on [2,4], use
kolmogorov_smirnov_test (x, "unif", 2, 4) |
dist can be any string for which a function dist_cdf that calculates the CDF of distribution dist exists.
With the optional argument string alt, the alternative of
interest can be selected. If alt is "!=" or
"<>", the null is tested against the two-sided alternative F
!= G. In this case, the test statistic ks follows a two-sided
Kolmogorov-Smirnov distribution. If alt is ">", the
one-sided alternative F > G is considered. Similarly for "<",
the one-sided alternative F > G is considered. In this case, the
test statistic ks has a one-sided Kolmogorov-Smirnov
distribution. The default is the two-sided case.
The p-value of the test is returned in pval.
If no output argument is given, the p-value is displayed.
Perform a 2-sample Kolmogorov-Smirnov test of the null hypothesis that the samples x and y come from the same (continuous) distribution. I.e., if F and G are the CDFs corresponding to the x and y samples, respectively, then the null is that F == G.
With the optional argument string alt, the alternative of
interest can be selected. If alt is "!=" or
"<>", the null is tested against the two-sided alternative F
!= G. In this case, the test statistic ks follows a two-sided
Kolmogorov-Smirnov distribution. If alt is ">", the
one-sided alternative F > G is considered. Similarly for "<",
the one-sided alternative F < G is considered. In this case, the
test statistic ks has a one-sided Kolmogorov-Smirnov
distribution. The default is the two-sided case.
The p-value of the test is returned in pval.
The third returned value, d, is the test statistic, the maximum vertical distance between the two cumulative distribution functions.
If no output argument is given, the p-value is displayed.
Perform a Kruskal-Wallis one-factor analysis of variance.
Suppose a variable is observed for k > 1 different groups, and let x1, …, xk be the corresponding data vectors.
Under the null hypothesis that the ranks in the pooled sample are not affected by the group memberships, the test statistic k is approximately chi-square with df = k - 1 degrees of freedom.
If the data contains ties (some value appears more than once) k is divided by
1 - sum_ties / (n^3 - n)
where sum_ties is the sum of t^2 - t over each group of ties where t is the number of ties in the group and n is the total number of values in the input data. For more info on this adjustment see William H. Kruskal and W. Allen Wallis, Use of Ranks in One-Criterion Variance Analysis, Journal of the American Statistical Association, Vol. 47, No. 260 (Dec 1952).
The p-value (1 minus the CDF of this distribution at k) is returned in pval.
If no output argument is given, the p-value is displayed.
Perform a one-way multivariate analysis of variance (MANOVA). The goal is to test whether the p-dimensional population means of data taken from k different groups are all equal. All data are assumed drawn independently from p-dimensional normal distributions with the same covariance matrix.
The data matrix is given by x. As usual, rows are observations and columns are variables. The vector g specifies the corresponding group labels (e.g., numbers from 1 to k).
The LR test statistic (Wilks’ Lambda) and approximate p-values are computed and displayed.
For a square contingency table x of data cross-classified on the row and column variables, McNemar’s test can be used for testing the null hypothesis of symmetry of the classification probabilities.
Under the null, chisq is approximately distributed as chisquare with df degrees of freedom.
The p-value (1 minus the CDF of this distribution at chisq) is returned in pval.
If no output argument is given, the p-value of the test is displayed.
If x1 and n1 are the counts of successes and trials in one sample, and x2 and n2 those in a second one, test the null hypothesis that the success probabilities p1 and p2 are the same. Under the null, the test statistic z approximately follows a standard normal distribution.
With the optional argument string alt, the alternative of
interest can be selected. If alt is "!=" or
"<>", the null is tested against the two-sided alternative
p1 != p2. If alt is ">", the one-sided
alternative p1 > p2 is used. Similarly for "<",
the one-sided alternative p1 < p2 is used.
The default is the two-sided case.
The p-value of the test is returned in pval.
If no output argument is given, the p-value of the test is displayed.
Perform a chi-square test with 6 degrees of freedom based on the upward runs in the columns of x. Can be used to test whether x contains independent data.
The p-value of the test is returned in pval.
If no output argument is given, the p-value is displayed.
For two matched-pair samples x and y, perform a sign test
of the null hypothesis PROB (x > y) == PROB (x <
y) == 1/2. Under the null, the test statistic b roughly
follows a binomial distribution with parameters n = sum
(x != y) and p = 1/2.
With the optional argument alt, the alternative of interest
can be selected. If alt is "!=" or "<>", the
null hypothesis is tested against the two-sided alternative PROB
(x < y) != 1/2. If alt is ">", the
one-sided alternative PROB (x > y) > 1/2 ("x is
stochastically greater than y") is considered. Similarly for
"<", the one-sided alternative PROB (x > y) < 1/2
("x is stochastically less than y") is considered. The default is
the two-sided case.
The p-value of the test is returned in pval.
If no output argument is given, the p-value of the test is displayed.
For a sample x from a normal distribution with unknown mean and
variance, perform a t-test of the null hypothesis mean
(x) == m. Under the null, the test statistic t
follows a Student distribution with df = length (x)
- 1 degrees of freedom.
With the optional argument string alt, the alternative of
interest can be selected. If alt is "!=" or
"<>", the null is tested against the two-sided alternative
mean (x) != m. If alt is ">", the
one-sided alternative mean (x) > m is considered.
Similarly for "<", the one-sided alternative mean
(x) < m is considered. The default is the two-sided
case.
The p-value of the test is returned in pval.
If no output argument is given, the p-value of the test is displayed.
For two samples x and y from normal distributions with unknown means and unknown equal variances, perform a two-sample t-test of the null hypothesis of equal means. Under the null, the test statistic t follows a Student distribution with df degrees of freedom.
With the optional argument string alt, the alternative of
interest can be selected. If alt is "!=" or
"<>", the null is tested against the two-sided alternative
mean (x) != mean (y). If alt is ">",
the one-sided alternative mean (x) > mean (y) is
used. Similarly for "<", the one-sided alternative mean
(x) < mean (y) is used. The default is the two-sided
case.
The p-value of the test is returned in pval.
If no output argument is given, the p-value of the test is displayed.
Perform a t test for the null hypothesis
rr * b = r in a classical normal
regression model y = x * b + e. Under the
null, the test statistic t follows a t distribution with
df degrees of freedom.
If r is omitted, a value of 0 is assumed.
With the optional argument string alt, the alternative of
interest can be selected. If alt is "!=" or
"<>", the null is tested against the two-sided alternative
rr * b != r. If alt is ">",
the one-sided alternative
rr * b > r is used. Similarly for
"<", the one-sided alternative
rr * b < r is used. The default is the
two-sided case.
The p-value of the test is returned in pval.
If no output argument is given, the p-value of the test is displayed.
For two samples x and y, perform a Mann-Whitney U-test of the null hypothesis PROB (x > y) == 1/2 == PROB (x < y). Under the null, the test statistic z approximately follows a standard normal distribution. Note that this test is equivalent to the Wilcoxon rank-sum test.
With the optional argument string alt, the alternative of
interest can be selected. If alt is "!=" or
"<>", the null is tested against the two-sided alternative
PROB (x > y) != 1/2. If alt is ">", the
one-sided alternative PROB (x > y) > 1/2 is considered.
Similarly for "<", the one-sided alternative PROB (x >
y) < 1/2 is considered. The default is the two-sided case.
The p-value of the test is returned in pval.
If no output argument is given, the p-value of the test is displayed.
For two samples x and y from normal distributions with unknown means and unknown variances, perform an F-test of the null hypothesis of equal variances. Under the null, the test statistic f follows an F-distribution with df_num and df_den degrees of freedom.
With the optional argument string alt, the alternative of
interest can be selected. If alt is "!=" or
"<>", the null is tested against the two-sided alternative
var (x) != var (y). If alt is ">",
the one-sided alternative var (x) > var (y) is
used. Similarly for "<", the one-sided alternative var
(x) > var (y) is used. The default is the two-sided
case.
The p-value of the test is returned in pval.
If no output argument is given, the p-value of the test is displayed.
For two samples x and y from normal distributions with unknown means and unknown and not necessarily equal variances, perform a Welch test of the null hypothesis of equal means. Under the null, the test statistic t approximately follows a Student distribution with df degrees of freedom.
With the optional argument string alt, the alternative of
interest can be selected. If alt is "!=" or
"<>", the null is tested against the two-sided alternative
mean (x) != m. If alt is ">", the
one-sided alternative mean(x) > m is considered. Similarly for
"<", the one-sided alternative mean(x) < m is
considered. The default is the two-sided case.
The p-value of the test is returned in pval.
If no output argument is given, the p-value of the test is displayed.
For two matched-pair sample vectors x and y, perform a Wilcoxon signed-rank test of the null hypothesis PROB (x > y) == 1/2. Under the null, the test statistic z approximately follows a standard normal distribution when n > 25.
Caution: This function assumes a normal distribution for z and thus is invalid for n ≤ 25.
With the optional argument string alt, the alternative of
interest can be selected. If alt is "!=" or
"<>", the null is tested against the two-sided alternative
PROB (x > y) != 1/2. If alt is ">", the one-sided
alternative PROB (x > y) > 1/2 is considered. Similarly
for "<", the one-sided alternative PROB (x > y) <
1/2 is considered. The default is the two-sided case.
The p-value of the test is returned in pval.
If no output argument is given, the p-value of the test is displayed.
Perform a Z-test of the null hypothesis mean (x) ==
m for a sample x from a normal distribution with unknown
mean and known variance v. Under the null, the test statistic
z follows a standard normal distribution.
With the optional argument string alt, the alternative of
interest can be selected. If alt is "!=" or
"<>", the null is tested against the two-sided alternative
mean (x) != m. If alt is ">", the
one-sided alternative mean (x) > m is considered.
Similarly for "<", the one-sided alternative mean
(x) < m is considered. The default is the two-sided
case.
The p-value of the test is returned in pval.
If no output argument is given, the p-value of the test is displayed along with some information.
For two samples x and y from normal distributions with unknown means and known variances v_x and v_y, perform a Z-test of the hypothesis of equal means. Under the null, the test statistic z follows a standard normal distribution.
With the optional argument string alt, the alternative of
interest can be selected. If alt is "!=" or
"<>", the null is tested against the two-sided alternative
mean (x) != mean (y). If alt is ">", the
one-sided alternative mean (x) > mean (y) is used.
Similarly for "<", the one-sided alternative mean
(x) < mean (y) is used. The default is the two-sided
case.
The p-value of the test is returned in pval.
If no output argument is given, the p-value of the test is displayed along with some information.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave can generate random numbers from a large number of distributions. The random number generators are based on the random number generators described in Special Utility Matrices.
The following table summarizes the available random number generators (in alphabetical order).
| Distribution | Function |
|---|---|
| Beta Distribution | betarnd |
| Binomial Distribution | binornd |
| Cauchy Distribution | cauchy_rnd |
| Chi-Square Distribution | chi2rnd |
| Univariate Discrete Distribution | discrete_rnd |
| Empirical Distribution | empirical_rnd |
| Exponential Distribution | exprnd |
| F Distribution | frnd |
| Gamma Distribution | gamrnd |
| Geometric Distribution | geornd |
| Hypergeometric Distribution | hygernd |
| Laplace Distribution | laplace_rnd |
| Logistic Distribution | logistic_rnd |
| Log-Normal Distribution | lognrnd |
| Pascal Distribution | nbinrnd |
| Univariate Normal Distribution | normrnd |
| Poisson Distribution | poissrnd |
| Standard Normal Distribution | stdnormal_rnd |
| t (Student) Distribution | trnd |
| Univariate Discrete Distribution | unidrnd |
| Uniform Distribution | unifrnd |
| Weibull Distribution | wblrnd |
| Wiener Process | wienrnd |
Return a matrix of random samples from the Beta distribution with parameters a and b.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the common size of a and b.
Return a matrix of random samples from the binomial distribution with parameters n and p, where n is the number of trials and p is the probability of success.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the common size of n and p.
Return a matrix of random samples from the Cauchy distribution with parameters location and scale.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the common size of location and scale.
Return a matrix of random samples from the chi-square distribution with n degrees of freedom.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the size of n.
Return a matrix of random samples from the univariate distribution which assumes the values in v with probabilities p.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the common size of v and p.
Return a matrix of random samples from the empirical distribution obtained from the univariate sample data.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is a random ordering of the sample data.
Return a matrix of random samples from the exponential distribution with mean lambda.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the size of lambda.
Return a matrix of random samples from the F distribution with m and n degrees of freedom.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the common size of m and n.
Return a matrix of random samples from the Gamma distribution with shape parameter a and scale b.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the common size of a and b.
Return a matrix of random samples from the geometric distribution with parameter p.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the size of p.
The geometric distribution models the number of failures (x-1) of a Bernoulli trial with probability p before the first success (x).
Return a matrix of random samples from the hypergeometric distribution with parameters t, m, and n.
The parameters t, m, and n must be positive integers with m and n not greater than t.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the common size of t, m, and n.
Return a matrix of random samples from the Laplace distribution.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
Return a matrix of random samples from the logistic distribution.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
Return a matrix of random samples from the lognormal distribution with parameters mu and sigma.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the common size of mu and sigma.
Return a matrix of random samples from the negative binomial distribution with parameters n and p.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the common size of n and p.
Return a matrix of random samples from the normal distribution with parameters mean mu and standard deviation sigma.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the common size of mu and sigma.
Return a matrix of random samples from the Poisson distribution with parameter lambda.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the size of lambda.
Return a matrix of random samples from the standard normal distribution (mean = 0, standard deviation = 1).
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
Return a matrix of random samples from the t (Student) distribution with n degrees of freedom.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the size of n.
Return a matrix of random samples from the discrete uniform distribution which assumes the integer values 1–n with equal probability. n may be a scalar or a multi-dimensional array.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the size of n.
Return a matrix of random samples from the uniform distribution on [a, b].
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the common size of a and b.
Return a matrix of random samples from the Weibull distribution with parameters scale and shape.
When called with a single size argument, return a square matrix with the dimension specified. When called with more than one scalar argument the first two arguments are taken as the number of rows and columns and any further arguments specify additional matrix dimensions. The size may also be specified with a vector of dimensions sz.
If no size arguments are given then the result matrix is the common size of scale and shape.
Return a simulated realization of the d-dimensional Wiener Process on the interval [0, t]. If d is omitted, d = 1 is used. The first column of the return matrix contains time, the remaining columns contain the Wiener process.
The optional parameter n gives the number of summands used for simulating the process over an interval of length 1. If n is omitted, n = 1000 is used.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave has a limited number of functions for managing sets of data, where a set is defined as a collection of unique elements. In Octave a set is represented as a vector of numbers.
Return the unique elements of x, sorted in ascending order. If the input x is a vector then the output is also a vector with the same orientation (row or column) as the input. For a matrix input the output is always a column vector. x may also be a cell array of strings.
If the optional argument "rows" is supplied, return the unique
rows of x, sorted in ascending order.
If requested, return index vectors i and j such that
x(i)==y and y(j)==x.
Additionally, if i is a requested output then one of "first" or
"last" may be given as an input. If "last" is specified,
return the highest possible indices in i, otherwise, if "first"
is specified, return the lowest. The default is "last".
| 27.1 Set Operations |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave supports the basic set operations. That is, Octave can compute
the union, intersection, and difference of two sets.
Octave also supports the Exclusive Or set operation, and
membership determination. The functions for set operations all work in
pretty much the same way. As an example, assume that x and
y contains two sets, then
union (x, y) |
computes the union of the two sets.
Return a logical matrix tf with the same shape as A which is
true (1) if A(i,j) is in s and false (0) if it is not. If a
second output argument is requested, the index into s of each of the
matching elements is also returned.
a = [3, 10, 1];
s = [0:9];
[tf, s_idx] = ismember (a, s)
⇒ tf = [1, 0, 1]
⇒ s_idx = [4, 0, 2]
|
The inputs, A and s, may also be cell arrays.
a = {"abc"};
s = {"abc", "def"};
[tf, s_idx] = ismember (a, s)
⇒ tf = [1, 0]
⇒ s_idx = [1, 0]
|
With the optional third argument "rows", and matrices
A and s with the same number of columns, compare rows in
A with the rows in s.
a = [1:3; 5:7; 4:6];
s = [0:2; 1:3; 2:4; 3:5; 4:6];
[tf, s_idx] = ismember (a, s, "rows")
⇒ tf = logical ([1; 0; 1])
⇒ s_idx = [2; 0; 5];
|
Return the set of elements that are in either of the sets a and b. a, b may be cell arrays of strings. For example:
union ([1, 2, 4], [2, 3, 5])
⇒ [1, 2, 3, 4, 5]
|
If the optional third input argument is the string "rows" then
each row of the matrices a and b will be considered as a
single set element. For example:
union ([1, 2; 2, 3], [1, 2; 3, 4], "rows")
⇒ 1 2
2 3
3 4
|
The optional outputs ia and ib are index vectors such that
a(ia) and b(ib) are disjoint sets whose union is c.
Return the elements in both a and b, sorted in ascending order. If a and b are both column vectors return a column vector, otherwise return a row vector. a, b may be cell arrays of string(s).
Return index vectors ia and ib such that a(ia)==c and
b(ib)==c.
See also: unique, union, setxor, setdiff, ismember.
Return the elements in a that are not in b, sorted in ascending order. If a and b are both column vectors return a column vector, otherwise return a row vector. a, b may be cell arrays of string(s).
Given the optional third argument "rows", return the rows in
a that are not in b, sorted in ascending order by rows.
If requested, return i such that c = a(i).
Return the elements exclusive to a or b, sorted in ascending order. If a and b are both column vectors return a column vector, otherwise return a row vector. a, b may be cell arrays of string(s).
With three output arguments, return index vectors ia and ib
such that a(ia) and b(ib) are disjoint sets whose union
is c.
Compute the powerset (all subsets) of the set a.
The set a must be a numerical matrix or a cell array of strings. The output will always be a cell array of either vectors or strings.
With the optional second argument "rows", each row of the set a
is considered one element of the set. As a result, a must then be a
numerical 2-D matrix.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In Octave, a polynomial is represented by its coefficients (arranged in descending order). For example, a vector c of length N+1 corresponds to the following polynomial of order N
p(x) = c(1) x^N + … + c(N) x + c(N+1). |
| 28.1 Evaluating Polynomials | ||
| 28.2 Finding Roots | ||
| 28.3 Products of Polynomials | ||
| 28.4 Derivatives / Integrals / Transforms | ||
| 28.5 Polynomial Interpolation | ||
| 28.6 Miscellaneous Functions |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The value of a polynomial represented by the vector c can be evaluated at the point x very easily, as the following example shows:
N = length (c) - 1; val = dot (x.^(N:-1:0), c); |
While the above example shows how easy it is to compute the value of a
polynomial, it isn’t the most stable algorithm. With larger polynomials
you should use more elegant algorithms, such as Horner’s Method, which
is exactly what the Octave function polyval does.
In the case where x is a square matrix, the polynomial given by
c is still well-defined. As when x is a scalar the obvious
implementation is easily expressed in Octave, but also in this case
more elegant algorithms perform better. The polyvalm function
provides such an algorithm.
Evaluate the polynomial p at the specified values of x. When mu is present, evaluate the polynomial for (x-mu(1))/mu(2). If x is a vector or matrix, the polynomial is evaluated for each of the elements of x.
In addition to evaluating the polynomial, the second output
represents the prediction interval, y +/- dy, which
contains at least 50% of the future predictions. To calculate the
prediction interval, the structured variable s, originating
from polyfit, must be supplied.
See also: polyvalm, polyaffine, polyfit, roots, poly.
Evaluate a polynomial in the matrix sense.
polyvalm (c, x) will evaluate the polynomial in the
matrix sense, i.e., matrix multiplication is used instead of element by
element multiplication as used in polyval.
The argument x must be a square matrix.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave can find the roots of a given polynomial. This is done by computing
the companion matrix of the polynomial (see the compan function
for a definition), and then finding its eigenvalues.
For a vector v with N components, return the roots of the polynomial
v(1) * z^(N-1) + … + v(N-1) * z + v(N) |
As an example, the following code finds the roots of the quadratic polynomial
p(x) = x^2 - 5. |
c = [1, 0, -5]; roots (c) ⇒ 2.2361 ⇒ -2.2361 |
Note that the true result is +/- sqrt(5) which is roughly +/- 2.2361.
Solve the polynomial eigenvalue problem of degree l.
Given an n*n matrix polynomial
C(s) = C0 + C1 s + … + Cl s^l
polyeig solves the eigenvalue problem
(C0 + C1 + … + Cl)v = 0.
Note that the eigenvalues z are the zeros of the matrix polynomial.
z is an lxn vector and v is an (n x n)l matrix
with columns that correspond to the eigenvectors.
Compute the companion matrix corresponding to polynomial coefficient vector c.
The companion matrix is
_ _
| -c(2)/c(1) -c(3)/c(1) … -c(N)/c(1) -c(N+1)/c(1) |
| 1 0 … 0 0 |
| 0 1 … 0 0 |
A = | . . . . . |
| . . . . . |
| . . . . . |
|_ 0 0 … 1 0 _|
|
The eigenvalues of the companion matrix are equal to the roots of the polynomial.
Identify unique poles in p and their associated multiplicity. The output is ordered from largest pole to smallest pole.
If the relative difference of two poles is less than tol then they are considered to be multiples. The default value for tol is 0.001.
If the optional parameter reorder is zero, poles are not sorted.
The output multp is a vector specifying the multiplicity of the
poles. multp(n) refers to the multiplicity of the Nth pole
p(idxp(n)).
For example:
p = [2 3 1 1 2]; [m, n] = mpoles (p) ⇒ m = [1; 1; 2; 1; 2] ⇒ n = [2; 5; 1; 4; 3] ⇒ p(n) = [3, 2, 2, 1, 1] |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Convolve two vectors a and b.
The output convolution is a vector with length equal to
length (a) + length (b) - 1.
When a and b are the coefficient vectors of two polynomials, the
convolution represents the coefficient vector of the product polynomial.
The optional shape argument may be
"full"Return the full convolution. (default)
"same"Return the central part of the convolution with the same size as a.
Return the n-D convolution of A and B. The size of the result is determined by the optional shape argument which takes the following values
"full"Return the full convolution. (default)
"same"Return central part of the convolution with the same size as A.
The central part of the convolution begins at the indices
floor ([size(B)/2] + 1).
"valid"Return only the parts which do not include zero-padded edges.
The size of the result is max (size (A) - size (B) + 1, 0).
Deconvolve two vectors.
[b, r] = deconv (y, a) solves for b and r such that
y = conv (a, b) + r.
If y and a are polynomial coefficient vectors, b will contain the coefficients of the polynomial quotient and r will be a remainder polynomial of lowest order.
Return the 2-D convolution of A and B. The size of the result is determined by the optional shape argument which takes the following values
"full"Return the full convolution. (default)
"same"Return the central part of the convolution with the same size as A.
The central part of the convolution begins at the indices
floor ([size(B)/2] + 1).
"valid"Return only the parts which do not include zero-padded edges.
The size of the result is max (size (A) - size (B) + 1, 0).
When the third argument is a matrix, return the convolution of the matrix m by the vector v1 in the column direction and by the vector v2 in the row direction.
Find the greatest common divisor of two polynomials. This is equivalent
to the polynomial found by multiplying together all the common roots.
Together with deconv, you can reduce a ratio of two polynomials.
The tolerance tol defaults to sqrt (eps).
Caution: This is a numerically unstable algorithm and should not be used on large polynomials.
Example code:
polygcd (poly (1:8), poly (3:12)) - poly (3:8) ⇒ [ 0, 0, 0, 0, 0, 0, 0 ] deconv (poly (1:8), polygcd (poly (1:8), poly (3:12))) - poly (1:2) ⇒ [ 0, 0, 0 ] |
The first calling form computes the partial fraction expansion for the quotient of the polynomials, b and a.
B(s) M r(m) N ---- = SUM ------------- + SUM k(i)*s^(N-i) A(s) m=1 (s-p(m))^e(m) i=1 |
where M is the number of poles (the length of the r, p, and e), the k vector is a polynomial of order N-1 representing the direct contribution, and the e vector specifies the multiplicity of the m-th residue’s pole.
For example,
b = [1, 1, 1]; a = [1, -5, 8, -4]; [r, p, k, e] = residue (b, a) ⇒ r = [-2; 7; 3] ⇒ p = [2; 2; 1] ⇒ k = [](0x0) ⇒ e = [1; 2; 1] |
which represents the following partial fraction expansion
s^2 + s + 1 -2 7 3 ------------------- = ----- + ------- + ----- s^3 - 5s^2 + 8s - 4 (s-2) (s-2)^2 (s-1) |
The second calling form performs the inverse operation and computes the reconstituted quotient of polynomials, b(s)/a(s), from the partial fraction expansion; represented by the residues, poles, and a direct polynomial specified by r, p and k, and the pole multiplicity e.
If the multiplicity, e, is not explicitly specified the multiplicity is
determined by the function mpoles.
For example:
r = [-2; 7; 3]; p = [2; 2; 1]; k = [1, 0]; [b, a] = residue (r, p, k) ⇒ b = [1, -5, 9, -3, 1] ⇒ a = [1, -5, 8, -4] where mpoles is used to determine e = [1; 2; 1] |
Alternatively the multiplicity may be defined explicitly, for example,
r = [7; 3; -2]; p = [2; 1; 2]; k = [1, 0]; e = [2; 1; 1]; [b, a] = residue (r, p, k, e) ⇒ b = [1, -5, 9, -3, 1] ⇒ a = [1, -5, 8, -4] |
which represents the following partial fraction expansion
-2 7 3 s^4 - 5s^3 + 9s^2 - 3s + 1 ----- + ------- + ----- + s = -------------------------- (s-2) (s-2)^2 (s-1) s^3 - 5s^2 + 8s - 4 |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave comes with functions for computing the derivative and the integral
of a polynomial. The functions polyder and polyint
both return new polynomials describing the result. As an example we’ll
compute the definite integral of p(x) = x^2 + 1 from 0 to 3.
c = [1, 0, 1]; integral = polyint (c); area = polyval (integral, 3) - polyval (integral, 0) ⇒ 12 |
Return the coefficients of the derivative of the polynomial whose coefficients are given by the vector p. If a pair of polynomials is given, return the derivative of the product a*b. If two inputs and two outputs are given, return the derivative of the polynomial quotient b/a. The quotient numerator is in q and the denominator in d.
See also: polyint, polyval, polyreduce.
Return the coefficients of the integral of the polynomial whose coefficients are represented by the vector p. The variable k is the constant of integration, which by default is set to zero.
Return the coefficients of the polynomial vector f after an affine
transformation. If f is the vector representing the polynomial f(x),
then g = polyaffine (f, mu) is the vector
representing:
g(x) = f( (x - mu(1)) / mu(2) ) |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave comes with good support for various kinds of interpolation,
most of which are described in Interpolation. One simple alternative
to the functions described in the aforementioned chapter, is to fit
a single polynomial, or a piecewise polynomial (spline) to some given
data points. To avoid a highly fluctuating polynomial, one most often
wants to fit a low-order polynomial to data. This usually means that it
is necessary to fit the polynomial in a least-squares sense, which just
is what the polyfit function does.
Return the coefficients of a polynomial p(x) of degree
n that minimizes the least-squares-error of the fit to the points
[x, y]. If n is a logical vector, it is used
as a mask to selectively force the corresponding polynomial
coefficients to be used or ignored.
The polynomial coefficients are returned in a row vector.
The optional output s is a structure containing the following fields:
Triangular factor R from the QR decomposition.
The Vandermonde matrix used to compute the polynomial coefficients.
The unscaled covariance matrix, formally equal to the inverse of x’*x, but computed in a way minimizing roundoff error propagation.
The degrees of freedom.
The norm of the residuals.
The values of the polynomial for each value of x.
The second output may be used by polyval to calculate the
statistical error limits of the predicted values. In particular, the
standard deviation of p coefficients is given by
sqrt (diag (s.C)/s.df)*s.normr.
When the third output, mu, is present the coefficients, p, are associated with a polynomial in xhat = (x-mu(1))/mu(2). Where mu(1) = mean (x), and mu(2) = std (x). This linear transformation of x improves the numerical stability of the fit.
See also: polyval, polyaffine, roots, vander, zscore.
In situations where a single polynomial isn’t good enough, a solution
is to use several polynomials pieced together. The function
splinefit fits a peicewise polynomial (spline) to a set of
data.
Fit a piecewise cubic spline with breaks (knots) breaks to the noisy data, x and y. x is a vector, and y is a vector or N-D array. If y is an N-D array, then x(j) is matched to y(:,…,:,j).
The fitted spline is returned as a piecewise polynomial, pp, and
may be evaluated using ppval.
p is a positive integer defining the number of intervals along x, and p+1 is the number of breaks. The number of points in each interval differ by no more than 1.
The optional property periodic is a logical value which specifies
whether a periodic boundary condition is applied to the spline. The
length of the period is max (breaks) - min (breaks).
The default value is false.
The optional property robust is a logical value which specifies if robust fitting is to be applied to reduce the influence of outlying data points. Three iterations of weighted least squares are performed. Weights are computed from previous residuals. The sensitivity of outlier identification is controlled by the property beta. The value of beta is stricted to the range, 0 < beta < 1. The default value is beta = 1/2. Values close to 0 give all data equal weighting. Increasing values of beta reduce the influence of outlying data. Values close to unity may cause instability or rank deficiency.
The splines are constructed of polynomials with degree order. The default is a cubic, order=3. A spline with P pieces has P+order degrees of freedom. With periodic boundary conditions the degrees of freedom are reduced to P.
The optional property, constaints, is a structure specifying
linear constraints on the fit. The structure has three fields, "xc",
"yc", and "cc".
"xc"Vector of the x-locations of the constraints.
"yc"Constraining values at the locations xc. The default is an array of zeros.
"cc"Coefficients (matrix). The default is an array of ones. The number of rows is limited to the order of the piecewise polynomials, order.
Constraints are linear combinations of derivatives of order 0 to order-1 according to
cc(1,j) * y(xc(j)) + cc(2,j) * y'(xc(j)) + ... = yc(:,...,:,j). |
See also: interp1, unmkpp, ppval, spline, pchip, ppder, ppint, ppjumps.
The number of breaks (or knots) used to construct the piecewise polynomial is a significant factor in suppressing the noise present in the input data, x and y. This is demonstrated by the example below.
x = 2 * pi * rand (1, 200);
y = sin (x) + sin (2 * x) + 0.2 * randn (size (x));
## Uniform breaks
breaks = linspace (0, 2 * pi, 41); % 41 breaks, 40 pieces
pp1 = splinefit (x, y, breaks);
## Breaks interpolated from data
pp2 = splinefit (x, y, 10); % 11 breaks, 10 pieces
## Plot
xx = linspace (0, 2 * pi, 400);
y1 = ppval (pp1, xx);
y2 = ppval (pp2, xx);
plot (x, y, ".", xx, [y1; y2])
axis tight
ylim auto
legend ({"data", "41 breaks, 40 pieces", "11 breaks, 10 pieces"})
|
The result of which can be seen in fig:splinefit1.
Figure 28.1: Comparison of a fitting a piecewise polynomial with 41 breaks to one with 11 breaks. The fit with the large number of breaks exhibits a fast ripple that is not present in the underlying function.
The piecewise polynomial fit, provided by splinefit, has
continuous derivatives up to the order-1. For example, a cubic fit
has continuous first and second derivatives. This is demonstrated by
the code
## Data (200 points)
x = 2 * pi * rand (1, 200);
y = sin (x) + sin (2 * x) + 0.1 * randn (size (x));
## Piecewise constant
pp1 = splinefit (x, y, 8, "order", 0);
## Piecewise linear
pp2 = splinefit (x, y, 8, "order", 1);
## Piecewise quadratic
pp3 = splinefit (x, y, 8, "order", 2);
## Piecewise cubic
pp4 = splinefit (x, y, 8, "order", 3);
## Piecewise quartic
pp5 = splinefit (x, y, 8, "order", 4);
## Plot
xx = linspace (0, 2 * pi, 400);
y1 = ppval (pp1, xx);
y2 = ppval (pp2, xx);
y3 = ppval (pp3, xx);
y4 = ppval (pp4, xx);
y5 = ppval (pp5, xx);
plot (x, y, ".", xx, [y1; y2; y3; y4; y5])
axis tight
ylim auto
legend ({"data", "order 0", "order 1", "order 2", "order 3", "order 4"})
|
The result of which can be seen in fig:splinefit2.
Figure 28.2: Comparison of a piecewise constant, linear, quadratic, cubic, and quartic polynomials with 8 breaks to noisy data. The higher order solutions more accurately represent the underlying function, but come with the expense of computational complexity.
When the underlying function to provide a fit to is periodic, splinefit
is able to apply the boundary conditions needed to manifest a periodic fit.
This is demonstrated by the code below.
## Data (100 points)
x = 2 * pi * [0, (rand (1, 98)), 1];
y = sin (x) - cos (2 * x) + 0.2 * randn (size (x));
## No constraints
pp1 = splinefit (x, y, 10, "order", 5);
## Periodic boundaries
pp2 = splinefit (x, y, 10, "order", 5, "periodic", true);
## Plot
xx = linspace (0, 2 * pi, 400);
y1 = ppval (pp1, xx);
y2 = ppval (pp2, xx);
plot (x, y, ".", xx, [y1; y2])
axis tight
ylim auto
legend ({"data", "no constraints", "periodic"})
|
The result of which can be seen in fig:splinefit3.
Figure 28.3: Comparison of piecewise polynomial fits to a noisy periodic function with, and without, periodic boundary conditions.
More complex constraints may be added as well. For example, the code below illustrates a periodic fit with values that have been clamped at the endpoints, and a second periodic fit which is hinged at the endpoints.
## Data (200 points)
x = 2 * pi * rand (1, 200);
y = sin (2 * x) + 0.1 * randn (size (x));
## Breaks
breaks = linspace (0, 2 * pi, 10);
## Clamped endpoints, y = y' = 0
xc = [0, 0, 2*pi, 2*pi];
cc = [(eye (2)), (eye (2))];
con = struct ("xc", xc, "cc", cc);
pp1 = splinefit (x, y, breaks, "constraints", con);
## Hinged periodic endpoints, y = 0
con = struct ("xc", 0);
pp2 = splinefit (x, y, breaks, "constraints", con, "periodic", true);
## Plot
xx = linspace (0, 2 * pi, 400);
y1 = ppval (pp1, xx);
y2 = ppval (pp2, xx);
plot (x, y, ".", xx, [y1; y2])
axis tight
ylim auto
legend ({"data", "clamped", "hinged periodic"})
|
The result of which can be seen in fig:splinefit4.
Figure 28.4: Comparison of two periodic piecewise cubic fits to a noisy periodic signal. One fit has its endpoints clamped and the second has its endpoints hinged.
The splinefit function also provides the convenience of a robust
fitting, where the effect of outlying data is reduced. In the example below,
three different fits are provided. Two with differing levels of outlier
suppression and a third illustrating the non-robust solution.
## Data
x = linspace (0, 2*pi, 200);
y = sin (x) + sin (2 * x) + 0.05 * randn (size (x));
## Add outliers
x = [x, linspace(0,2*pi,60)];
y = [y, -ones(1,60)];
## Fit splines with hinged conditions
con = struct ("xc", [0, 2*pi]);
## Robust fitting, beta = 0.25
pp1 = splinefit (x, y, 8, "constraints", con, "beta", 0.25);
## Robust fitting, beta = 0.75
pp2 = splinefit (x, y, 8, "constraints", con, "beta", 0.75);
## No robust fitting
pp3 = splinefit (x, y, 8, "constraints", con);
## Plot
xx = linspace (0, 2*pi, 400);
y1 = ppval (pp1, xx);
y2 = ppval (pp2, xx);
y3 = ppval (pp3, xx);
plot (x, y, ".", xx, [y1; y2; y3])
legend ({"data with outliers","robust, beta = 0.25", ...
"robust, beta = 0.75", "no robust fitting"})
axis tight
ylim auto
|
The result of which can be seen in fig:splinefit6.
Figure 28.5: Comparison of two different levels of robust fitting (beta = 0.25 and 0.75) to noisy data combined with outlying data. A conventional fit, without robust fitting (beta = 0) is also included.
The function, ppval, evaluates the piecewise polynomials, created
by mkpp or other means, and unmkpp returns detailed
information about the piecewise polynomial.
The following example shows how to combine two linear functions and a quadratic into one function. Each of these functions is expressed on adjoined intervals.
x = [-2, -1, 1, 2];
p = [ 0, 1, 0;
1, -2, 1;
0, -1, 1 ];
pp = mkpp (x, p);
xi = linspace (-2, 2, 50);
yi = ppval (pp, xi);
plot (xi, yi);
|
Construct a piecewise polynomial (pp) structure from sample points
breaks and coefficients coefs. breaks must be a vector of
strictly increasing values. The number of intervals is given by
ni = length (breaks) - 1.
When m is the polynomial order coefs must be of
size: ni x m + 1.
The i-th row of coefs,
coefs (i,:), contains the coefficients for the polynomial
over the i-th interval, ordered from highest (m) to
lowest (0).
coefs may also be a multi-dimensional array, specifying a vector-valued
or array-valued polynomial. In that case the polynomial order is defined
by the length of the last dimension of coefs.
The size of first dimension(s) are given by the scalar or
vector d. If d is not given it is set to 1.
In any case coefs is reshaped to a 2-D matrix of
size [ni*prod(d m)]
See also: unmkpp, ppval, spline, pchip, ppder, ppint, ppjumps.
Extract the components of a piecewise polynomial structure pp. The components are:
Sample points.
Polynomial coefficients for points in sample interval. p
(i, :) contains the coefficients for the polynomial over
interval i ordered from highest to lowest. If d >
1, p (r, i, :) contains the coefficients for
the r-th polynomial defined on interval i.
Number of polynomial pieces.
Order of the polynomial plus 1.
Number of polynomials defined for each interval.
Evaluate the piecewise polynomial structure pp at the points xi.
If pp describes a scalar polynomial function, the result is an
array of the same shape as xi.
Otherwise, the size of the result is [pp.dim, length(xi)] if
xi is a vector, or [pp.dim, size(xi)] if it is a
multi-dimensional array.
Compute the piecewise m-th derivative of a piecewise polynomial struct pp. If m is omitted the first derivative is calculated.
Compute the integral of the piecewise polynomial struct pp. c, if given, is the constant of integration.
Evaluate the boundary jumps of a piecewise polynomial.
If there are n intervals, and the dimensionality of pp is
d, the resulting array has dimensions [d, n-1].
See also: mkpp.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
If A is a square N-by-N matrix, poly (A)
is the row vector of the coefficients of det (z * eye (N) - A),
the characteristic polynomial of A. For example,
the following code finds the eigenvalues of A which are the roots of
poly (A).
roots (poly (eye (3)))
⇒ 1.00001 + 0.00001i
1.00001 - 0.00001i
0.99999 + 0.00000i
|
In fact, all three eigenvalues are exactly 1 which emphasizes that for
numerical performance the eig function should be used to compute
eigenvalues.
If x is a vector, poly (x) is a vector of the
coefficients of the polynomial whose roots are the elements of x.
That is, if c is a polynomial, then the elements of d =
roots (poly (c)) are contained in c. The vectors c and
d are not identical, however, due to sorting and numerical errors.
Write formatted polynomial
c(x) = c(1) * x^n + … + c(n) x + c(n+1) |
and return it as a string or write it to the screen (if nargout is
zero). x defaults to the string "s".
See also: polyreduce.
Reduce a polynomial coefficient vector to a minimum number of terms by stripping off any leading zeros.
See also: polyout.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 29.1 One-dimensional Interpolation | ||
| 29.2 Multi-dimensional Interpolation |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave supports several methods for one-dimensional interpolation, most of which are described in this section. Polynomial Interpolation and Interpolation on Scattered Data describe additional methods.
One-dimensional interpolation.
Interpolate input data to determine the value of yi at the points xi. If not specified, x is taken to be the indices of y. If y is a matrix or an N-dimensional array, the interpolation is performed on each column of y.
Method is one of:
"nearest"Return the nearest neighbor
"linear"Linear interpolation from nearest neighbors
"pchip"Piecewise cubic Hermite interpolating polynomial
"cubic"Cubic interpolation (same as pchip)
"spline"Cubic spline interpolation—smooth first and second derivatives throughout the curve
Adding ’*’ to the start of any method above forces interp1
to assume that x is uniformly spaced, and only x(1)
and x(2) are referenced. This is usually faster,
and is never slower. The default method is "linear".
If extrap is the string "extrap", then extrapolate values
beyond the endpoints using the current method. If extrap is a
number, then replace values beyond the endpoints with that number. When
unspecified, extrap defaults to NA.
If the string argument "pp" is specified, then xi should not
be supplied and interp1 returns a piecewise polynomial object. This
object can later be used with ppval to evaluate the interpolation.
There is an equivalence, such that ppval (interp1 (x,
y, method, .
"pp"), xi) == interp1 (x, y,
xi, method, "extrap")
Duplicate points in x specify a discontinuous interpolant. There
may be at most 2 consecutive points with the same value.
If x is increasing, the default discontinuous interpolant is
right-continuous. If x is decreasing, the default discontinuous
interpolant is left-continuous.
The continuity condition of the interpolant may be specified by using
the options, "left" or "right", to select a left-continuous
or right-continuous interpolant, respectively.
Discontinuous interpolation is only allowed for "nearest" and
"linear" methods; in all other cases, the x-values must be
unique.
An example of the use of interp1 is
xf = [0:0.05:10];
yf = sin (2*pi*xf/5);
xp = [0:10];
yp = sin (2*pi*xp/5);
lin = interp1 (xp, yp, xf);
spl = interp1 (xp, yp, xf, "spline");
cub = interp1 (xp, yp, xf, "cubic");
near = interp1 (xp, yp, xf, "nearest");
plot (xf, yf, "r", xf, lin, "g", xf, spl, "b",
xf, cub, "c", xf, near, "m", xp, yp, "r*");
legend ("original", "linear", "spline", "cubic", "nearest");
|
There are some important differences between the various interpolation
methods. The "spline" method enforces that both the first and second
derivatives of the interpolated values have a continuous derivative,
whereas the other methods do not. This means that the results of the
"spline" method are generally smoother. If the function to be
interpolated is in fact smooth, then "spline" will give excellent
results. However, if the function to be evaluated is in some manner
discontinuous, then "pchip" interpolation might give better results.
This can be demonstrated by the code
t = -2:2;
dt = 1;
ti =-2:0.025:2;
dti = 0.025;
y = sign (t);
ys = interp1 (t,y,ti,"spline");
yp = interp1 (t,y,ti,"pchip");
ddys = diff (diff (ys)./dti) ./ dti;
ddyp = diff (diff (yp)./dti) ./ dti;
figure (1);
plot (ti,ys,"r-", ti,yp,"g-");
legend ("spline", "pchip", 4);
figure (2);
plot (ti,ddys,"r+", ti,ddyp,"g*");
legend ("spline", "pchip");
|
The result of which can be seen in fig:interpderiv1 and fig:interpderiv2.
Figure 29.1: Comparison of "pchip" and "spline" interpolation methods for a
step function
Figure 29.2: Comparison of the second derivative of the "pchip" and "spline"
interpolation methods for a step function
Fourier interpolation, is a resampling technique where a signal is converted to the frequency domain, padded with zeros and then reconverted to the time domain.
Fourier interpolation. If x is a vector, then x is resampled with n points. The data in x is assumed to be equispaced. If x is a matrix or an N-dimensional array, the interpolation is performed on each column of x. If dim is specified, then interpolate along the dimension dim.
interpft assumes that the interpolated function is periodic,
and so assumptions are made about the endpoints of the interpolation.
See also: interp1.
There are two significant limitations on Fourier interpolation. First,
the function signal is assumed to be periodic, and so non-periodic
signals will be poorly represented at the edges. Second, both the
signal and its interpolation are required to be sampled at equispaced
points. An example of the use of interpft is
t = 0 : 0.3 : pi; dt = t(2)-t(1);
n = length (t); k = 100;
ti = t(1) + [0 : k-1]*dt*n/k;
y = sin (4*t + 0.3) .* cos (3*t - 0.1);
yp = sin (4*ti + 0.3) .* cos (3*ti - 0.1);
plot (ti, yp, "g", ti, interp1 (t, y, ti, "spline"), "b", ...
ti, interpft (y, k), "c", t, y, "r+");
legend ("sin(4t+0.3)cos(3t-0.1)", "spline", "interpft", "data");
|
which demonstrates the poor behavior of Fourier interpolation for non-periodic functions, as can be seen in fig:interpft.
Figure 29.3: Comparison of interp1 and interpft for non-periodic data
In addition, the support functions spline and lookup that
underlie the interp1 function can be called directly.
Return the cubic spline interpolant of points x and y.
When called with two arguments, return the piecewise polynomial pp
that may be used with ppval to evaluate the polynomial at specific
points. When called with a third input argument, spline evaluates
the spline at the points xi. The third calling form spline
(x, y, xi) is equivalent to ppval (spline
(x, y), xi).
The variable x must be a vector of length n. y can be
either a vector or array. If y is a vector it must have a length of
either n or n + 2. If the length of y is
n, then the "not-a-knot" end condition is used. If the length of
y is n + 2, then the first and last values of the
vector y are the values of the first derivative of the cubic spline
at the endpoints.
If y is an array, then the size of y must have the form
[s1, s2, …, sk, n]
or
[s1, s2, …, sk, n + 2].
The array is reshaped internally to a matrix where the leading
dimension is given by
s1 * s2 * … * sk
and each row of this matrix is then treated separately. Note that this
is exactly opposite to interp1 but is done for MATLAB
compatibility.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There are three multi-dimensional interpolation functions in Octave, with similar capabilities. Methods using Delaunay tessellation are described in Interpolation on Scattered Data.
Two-dimensional interpolation. x, y and z describe a
surface function. If x and y are vectors their length
must correspondent to the size of z. x and y must be
monotonic. If they are matrices they must have the meshgrid
format.
interp2 (x, y, Z, xi, yi, …)Returns a matrix corresponding to the points described by the matrices xi, yi.
If the last argument is a string, the interpolation method can
be specified. The method can be "linear", "nearest" or
"cubic". If it is omitted "linear" interpolation is
assumed.
interp2 (z, xi, yi)Assumes x = 1:rows (z) and y =
1:columns (z)
interp2 (z, n)Interleaves the matrix z n-times. If n is omitted a value
of n = 1 is assumed.
The variable method defines the method to use for the interpolation. It can take one of the following values
"nearest"Return the nearest neighbor.
"linear"Linear interpolation from nearest neighbors.
"pchip"Piecewise cubic Hermite interpolating polynomial.
"cubic"Cubic interpolation from four nearest neighbors.
"spline"Cubic spline interpolation—smooth first and second derivatives throughout the curve.
If a scalar value extrapval is defined as the final value, then values outside the mesh as set to this value. Note that in this case method must be defined as well. If extrapval is not defined then NA is assumed.
See also: interp1.
Perform 3-dimensional interpolation. Each element of the 3-dimensional
array v represents a value at a location given by the parameters
x, y, and z. The parameters x, x, and
z are either 3-dimensional arrays of the same size as the array
v in the "meshgrid" format or vectors. The parameters
xi, etc. respect a similar format to x, etc., and they
represent the points at which the array vi is interpolated.
If x, y, z are omitted, they are assumed to be
x = 1 : size (v, 2), y = 1 : size (v, 1) and
z = 1 : size (v, 3). If m is specified, then
the interpolation adds a point half way between each of the interpolation
points. This process is performed m times. If only v is
specified, then m is assumed to be 1.
Method is one of:
"nearest"Return the nearest neighbor.
"linear"Linear interpolation from nearest neighbors.
"cubic"Cubic interpolation from four nearest neighbors (not implemented yet).
"spline"Cubic spline interpolation—smooth first and second derivatives throughout the curve.
The default method is "linear".
If extrap is the string "extrap", then extrapolate values
beyond the endpoints. If extrap is a number, replace values beyond
the endpoints with that number. If extrap is missing, assume NA.
Perform n-dimensional interpolation, where n is at least two.
Each element of the n-dimensional array v represents a value
at a location given by the parameters x1, x2, …, xn.
The parameters x1, x2, …, xn are either
n-dimensional arrays of the same size as the array v in
the "ndgrid" format or vectors. The parameters y1, etc.
respect a similar format to x1, etc., and they represent the points
at which the array vi is interpolated.
If x1, …, xn are omitted, they are assumed to be
x1 = 1 : size (v, 1), etc. If m is specified, then
the interpolation adds a point half way between each of the interpolation
points. This process is performed m times. If only v is
specified, then m is assumed to be 1.
Method is one of:
"nearest"Return the nearest neighbor.
"linear"Linear interpolation from nearest neighbors.
"cubic"Cubic interpolation from four nearest neighbors (not implemented yet).
"spline"Cubic spline interpolation—smooth first and second derivatives throughout the curve.
The default method is "linear".
If extrapval is the scalar value, use it to replace the values beyond the endpoints with that number. If extrapval is missing, assume NA.
A significant difference between interpn and the other two
multi-dimensional interpolation functions is the fashion in which the
dimensions are treated. For interp2 and interp3, the y-axis is
considered to be the columns of the matrix, whereas the x-axis corresponds to
the rows of the array. As Octave indexes arrays in column major order, the
first dimension of any array is the columns, and so interpn effectively
reverses the ’x’ and ’y’ dimensions. Consider the example,
x = y = z = -1:1; f = @(x,y,z) x.^2 - y - z.^2; [xx, yy, zz] = meshgrid (x, y, z); v = f (xx,yy,zz); xi = yi = zi = -1:0.1:1; [xxi, yyi, zzi] = meshgrid (xi, yi, zi); vi = interp3 (x, y, z, v, xxi, yyi, zzi, "spline"); [xxi, yyi, zzi] = ndgrid (xi, yi, zi); vi2 = interpn (x, y, z, v, xxi, yyi, zzi, "spline"); mesh (zi, yi, squeeze (vi2(1,:,:))); |
where vi and vi2 are identical. The reversal of the
dimensions is treated in the meshgrid and ndgrid functions
respectively.
The result of this code can be seen in fig:interpn.
Figure 29.4: Demonstration of the use of interpn
In additional the support function bicubic that underlies the
cubic interpolation of interp2 function can be called directly.
Return a matrix zi corresponding to the bicubic interpolations at xi and yi of the data supplied as x, y and z. Points outside the grid are set to extrapval.
See http://wiki.woodpecker.org.cn/moin/Octave/Bicubic for further information.
See also: interp2.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Much of the geometry code in Octave is based on the Qhull
library(12).
Some of the documentation for Qhull, particularly for the options that
can be passed to delaunay, voronoi and convhull,
etc., is relevant to Octave users.
| 30.1 Delaunay Triangulation | ||
| 30.2 Voronoi Diagrams | ||
| 30.3 Convex Hull | ||
| 30.4 Interpolation on Scattered Data |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The Delaunay triangulation is constructed from a set of circum-circles. These circum-circles are chosen so that there are at least three of the points in the set to triangulation on the circumference of the circum-circle. None of the points in the set of points falls within any of the circum-circles.
In general there are only three points on the circumference of any circum-circle. However, in some cases, and in particular for the case of a regular grid, 4 or more points can be on a single circum-circle. In this case the Delaunay triangulation is not unique.
Compute the Delaunay triangulation for a 2-D set of points. The return value tri is a set of triangles which satisfies the Delaunay circum-circle criterion, i.e., only a single data point from [x, y] is within the circum-circle of the defining triangle. The input x may also be a matrix with two columns where the first column contains x-data and the second y-data.
The set of triangles tri is a matrix of size [n, 3]. Each
row defines a triangle and the three columns are the three vertices
of the triangle. The value of tri(i,j) is an index into
x and y for the location of the j-th vertex of the i-th
triangle.
The optional last argument, which must be a string or cell array of strings,
contains options passed to the underlying qhull command.
See the documentation for the Qhull library for details
http://www.qhull.org/html/qh-quick.htm#options.
The default options are {"Qt", "Qbb", "Qc", "Qz"}.
If options is not present or [] then the default arguments are
used. Otherwise, options replaces the default argument list.
To append user options to the defaults it is necessary to repeat the
default arguments in options. Use a null string to pass no arguments.
If no output argument is specified the resulting Delaunay triangulation is plotted along with the original set of points.
x = rand (1, 10); y = rand (1, 10); T = delaunay (x, y); VX = [ x(T(:,1)); x(T(:,2)); x(T(:,3)); x(T(:,1)) ]; VY = [ y(T(:,1)); y(T(:,2)); y(T(:,3)); y(T(:,1)) ]; axis ([0,1,0,1]); plot (VX, VY, "b", x, y, "r*"); |
See also: delaunay3, delaunayn, convhull, voronoi, triplot, trimesh, trisurf.
The 3- and N-dimensional extension of the Delaunay triangulation are
given by delaunay3 and delaunayn respectively.
delaunay3 returns a set of tetrahedra that satisfy the
Delaunay circum-circle criteria. Similarly, delaunayn returns the
N-dimensional simplex satisfying the Delaunay circum-circle criteria.
The N-dimensional extension of a triangulation is called a tessellation.
Compute the Delaunay triangulation for a 3-D set of points. The return value tetr is a set of tetrahedrons which satisfies the Delaunay circum-circle criterion, i.e., only a single data point from [x, y, z] is within the circum-circle of the defining tetrahedron.
The set of tetrahedrons tetr is a matrix of size [n, 4]. Each
row defines a tetrahedron and the four columns are the four vertices
of the tetrahedron. The value of tetr(i,j) is an index into
x, y, z for the location of the j-th vertex of the i-th
tetrahedron.
An optional fourth argument, which must be a string or cell array of strings,
contains options passed to the underlying qhull command.
See the documentation for the Qhull library for details
http://www.qhull.org/html/qh-quick.htm#options.
The default options are {"Qt", "Qbb", "Qc", "Qz"}.
If options is not present or [] then the default arguments are
used. Otherwise, options replaces the default argument list.
To append user options to the defaults it is necessary to repeat the
default arguments in options. Use a null string to pass no arguments.
See also: delaunay, delaunayn, convhull, voronoi, tetramesh.
Compute the Delaunay triangulation for an N-dimensional set of points. The Delaunay triangulation is a tessellation of the convex hull of a set of points such that no N-sphere defined by the N-triangles contains any other points from the set.
The input matrix pts of size [n, dim] contains n points in a space of dimension dim. The return matrix T has size [m, dim+1]. Each row of T contains a set of indices back into the original set of points pts which describes a simplex of dimension dim. For example, a 2-D simplex is a triangle and 3-D simplex is a tetrahedron.
An optional second argument, which must be a string or cell array of strings, contains options passed to the underlying qhull command. See the documentation for the Qhull library for details http://www.qhull.org/html/qh-quick.htm#options. The default options depend on the dimension of the input:
{"Qt", "Qbb", "Qc", "Qz"}
{"Qt", "Qbb", "Qc", "Qx"}
If options is not present or [] then the default arguments are
used. Otherwise, options replaces the default argument list.
To append user options to the defaults it is necessary to repeat the
default arguments in options. Use a null string to pass no arguments.
See also: delaunay, delaunay3, convhulln, voronoin, trimesh, tetramesh.
An example of a Delaunay triangulation of a set of points is
rand ("state", 2);
x = rand (10, 1);
y = rand (10, 1);
T = delaunay (x, y);
X = [ x(T(:,1)); x(T(:,2)); x(T(:,3)); x(T(:,1)) ];
Y = [ y(T(:,1)); y(T(:,2)); y(T(:,3)); y(T(:,1)) ];
axis ([0, 1, 0, 1]);
plot (X, Y, "b", x, y, "r*");
|
The result of which can be seen in fig:delaunay.
Figure 30.1: Delaunay triangulation of a random set of points
| 30.1.1 Plotting the Triangulation | ||
| 30.1.2 Identifying Points in Triangulation |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave has the functions triplot, trimesh, and trisurf
to plot the Delaunay triangulation of a 2-dimensional set of points.
tetramesh will plot the triangulation of a 3-dimensional set of points.
Plot a 2-D triangular mesh.
tri is typically the output of a Delaunay triangulation over the grid of x, y. Every row of tri represents one triangle and contains three indices into [x, y] which are the vertices of the triangles in the x-y plane.
The linestyle to use for the plot can be defined with the argument
linespec of the same format as the plot command.
The optional return value h is a graphics handle to the created patch object.
Plot a 3-D triangular wireframe mesh.
In contrast to mesh, which plots a mesh using rectangles,
trimesh plots the mesh using triangles.
tri is typically the output of a Delaunay triangulation over the grid of x, y. Every row of tri represents one triangle and contains three indices into [x, y] which are the vertices of the triangles in the x-y plane. z determines the height above the plane of each vertex. If no z input is given then the triangles are plotted as a 2-D figure.
The color of the trimesh is computed by linearly scaling the z values
to fit the range of the current colormap. Use caxis and/or
change the colormap to control the appearance.
Optionally, the color of the mesh can be specified independently of z by supplying a color matrix, c. If z has N elements, then c should be an Nx1 vector for colormap data or an Nx3 matrix for RGB data.
Any property/value pairs are passed directly to the underlying patch object.
The optional return value h is a graphics handle to the created patch object.
See also: mesh, tetramesh, triplot, trisurf, delaunay, patch, hidden.
Plot a 3-D triangular surface.
In contrast to surf, which plots a surface mesh using rectangles,
trisurf plots the mesh using triangles.
tri is typically the output of a Delaunay triangulation over the grid of x, y. Every row of tri represents one triangle and contains three indices into [x, y] which are the vertices of the triangles in the x-y plane. z determines the height above the plane of each vertex.
The color of the trimesh is computed by linearly scaling the z values
to fit the range of the current colormap. Use caxis and/or
change the colormap to control the appearance.
Optionally, the color of the mesh can be specified independently of z by supplying a color matrix, c. If z has N elements, then c should be an Nx1 vector for colormap data or an Nx3 matrix for RGB data.
Any property/value pairs are passed directly to the underlying patch object.
The optional return value h is a graphics handle to the created patch object.
Display the tetrahedrons defined in the m-by-4 matrix T as 3-D patches.
T is typically the output of a Delaunay triangulation of a 3-D set of points. Every row of T contains four indices into the n-by-3 matrix X of the vertices of a tetrahedron. Every row in X represents one point in 3-D space.
The vector C specifies the color of each tetrahedron as an index into the current colormap. The default value is 1:m where m is the number of tetrahedrons; the indices are scaled to map to the full range of the colormap. If there are more tetrahedrons than colors in the colormap then the values in C are cyclically repeated.
Calling tetramesh (…, "property", "value", …) passes all
property/value pairs directly to the patch function as additional arguments.
The optional return value h is a vector of patch handles where each
handle represents one tetrahedron in the order given by T.
A typical use case for h is to turn the respective patch
"visible" property "on" or "off".
Type demo tetramesh to see examples on using tetramesh.
The difference between triplot, and trimesh or triplot,
is that the former only plots the 2-dimensional triangulation itself, whereas
the second two plot the value of a function f (x, y). An
example of the use of the triplot function is
rand ("state", 2)
x = rand (20, 1);
y = rand (20, 1);
tri = delaunay (x, y);
triplot (tri, x, y);
|
which plots the Delaunay triangulation of a set of random points in 2-dimensions. The output of the above can be seen in fig:triplot.
Figure 30.2: Delaunay triangulation of a random set of points
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
It is often necessary to identify whether a particular point in the
N-dimensional space is within the Delaunay tessellation of a set of
points in this N-dimensional space, and if so which N-simplex contains
the point and which point in the tessellation is closest to the desired
point. The functions tsearch and dsearch perform this
function in a triangulation, and tsearchn and dsearchn in
an N-dimensional tessellation.
To identify whether a particular point represented by a vector p
falls within one of the simplices of an N-simplex, we can write the
Cartesian coordinates of the point in a parametric form with respect to
the N-simplex. This parametric form is called the Barycentric
Coordinates of the point. If the points defining the N-simplex are given
by N + 1 vectors t(i,:), then the Barycentric
coordinates defining the point p are given by
p = sum (beta(1:N+1) * t(1:N+1),:) |
where there are N + 1 values beta(i)
that together as a vector represent the Barycentric coordinates of the
point p. To ensure a unique solution for the values of
beta(i) an additional criteria of
sum (beta(1:N+1)) == 1 |
is imposed, and we can therefore write the above as
p - t(end, :) = beta(1:end-1) * (t(1:end-1, :)
- ones (N, 1) * t(end, :)
|
Solving for beta we can then write
beta(1:end-1) = (p - t(end, :)) / (t(1:end-1, :)
- ones (N, 1) * t(end, :))
beta(end) = sum (beta(1:end-1))
|
which gives the formula for the conversion of the Cartesian coordinates of the point p to the Barycentric coordinates beta. An important property of the Barycentric coordinates is that for all points in the N-simplex
0 <= beta(i) <= 1 |
Therefore, the test in tsearch and tsearchn essentially
only needs to express each point in terms of the Barycentric coordinates
of each of the simplices of the N-simplex and test the values of
beta. This is exactly the implementation used in
tsearchn. tsearch is optimized for 2-dimensions and the
Barycentric coordinates are not explicitly formed.
Search for the enclosing Delaunay convex hull. For t =
delaunay (x, y), finds the index in t containing the
points (xi, yi). For points outside the convex hull,
idx is NaN.
Search for the enclosing Delaunay convex hull. For t =
delaunayn (x), finds the index in t containing the
points xi. For points outside the convex hull, idx is NaN.
If requested tsearchn also returns the Barycentric coordinates p
of the enclosing triangles.
An example of the use of tsearch can be seen with the simple
triangulation
x = [-1; -1; 1; 1]; y = [-1; 1; -1; 1]; tri = [1, 2, 3; 2, 3, 1]; |
consisting of two triangles defined by tri. We can then identify which triangle a point falls in like
tsearch (x, y, tri, -0.5, -0.5) ⇒ 1 tsearch (x, y, tri, 0.5, 0.5) ⇒ 2 |
and we can confirm that a point doesn’t lie within one of the triangles like
tsearch (x, y, tri, 2, 2) ⇒ NaN |
The dsearch and dsearchn find the closest point in a
tessellation to the desired point. The desired point does not
necessarily have to be in the tessellation, and even if it the returned
point of the tessellation does not have to be one of the vertexes of the
N-simplex within which the desired point is found.
Return the index idx or the closest point in x, y
to the elements [xi(:), yi(:)]. The variable s is
accepted for compatibility but is ignored.
Return the index idx or the closest point in x to the elements
xi. If outval is supplied, then the values of xi that are
not contained within one of the simplices tri are set to
outval. Generally, tri is returned from delaunayn
(x).
An example of the use of dsearch, using the above values of
x, y and tri is
dsearch (x, y, tri, -2, -2) ⇒ 1 |
If you wish the points that are outside the tessellation to be flagged,
then dsearchn can be used as
dsearchn ([x, y], tri, [-2, -2], NaN) ⇒ NaN dsearchn ([x, y], tri, [-0.5, -0.5], NaN) ⇒ 1 |
where the point outside the tessellation are then flagged with NaN.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A Voronoi diagram or Voronoi tessellation of a set of points s in
an N-dimensional space, is the tessellation of the N-dimensional space
such that all points in v(p), a partitions of the
tessellation where p is a member of s, are closer to p
than any other point in s. The Voronoi diagram is related to the
Delaunay triangulation of a set of points, in that the vertexes of the
Voronoi tessellation are the centers of the circum-circles of the
simplices of the Delaunay tessellation.
Plot the Voronoi diagram of points (x, y).
The Voronoi facets with points at infinity are not drawn.
If "linespec" is given it is used to set the color and line style
of the plot. If an axis graphics handle hax is supplied then the
Voronoi diagram is drawn on the specified axis rather than in a new
figure.
The options argument, which must be a string or cell array of strings, contains options passed to the underlying qhull command. See the documentation for the Qhull library for details http://www.qhull.org/html/qh-quick.htm#options.
If a single output argument is requested then the Voronoi diagram will be plotted and a graphics handle h to the plot is returned. [vx, vy] = voronoi (…) returns the Voronoi vertices instead of plotting the diagram.
x = rand (10, 1);
y = rand (size (x));
h = convhull (x, y);
[vx, vy] = voronoi (x, y);
plot (vx, vy, "-b", x, y, "o", x(h), y(h), "-g");
legend ("", "points", "hull");
|
Compute N-dimensional Voronoi facets. The input matrix pts of size [n, dim] contains n points in a space of dimension dim. C contains the points of the Voronoi facets. The list F contains, for each facet, the indices of the Voronoi points.
An optional second argument, which must be a string or cell array of strings, contains options passed to the underlying qhull command. See the documentation for the Qhull library for details http://www.qhull.org/html/qh-quick.htm#options.
The default options depend on the dimension of the input:
{"Qbb"}
{"Qbb", "Qx"}
If options is not present or [] then the default arguments are
used. Otherwise, options replaces the default argument list.
To append user options to the defaults it is necessary to repeat the
default arguments in options. Use a null string to pass no arguments.
An example of the use of voronoi is
rand ("state",9);
x = rand (10,1);
y = rand (10,1);
tri = delaunay (x, y);
[vx, vy] = voronoi (x, y, tri);
triplot (tri, x, y, "b");
hold on;
plot (vx, vy, "r");
|
The result of which can be seen in fig:voronoi. Note that the circum-circle of one of the triangles has been added to this figure, to make the relationship between the Delaunay tessellation and the Voronoi diagram clearer.
Figure 30.3: Delaunay triangulation and Voronoi diagram of a random set of points
Additional information about the size of the facets of a Voronoi
diagram, and which points of a set of points is in a polygon can be had
with the polyarea and inpolygon functions respectively.
Determine area of a polygon by triangle method. The variables x and y define the vertex pairs, and must therefore have the same shape. They can be either vectors or arrays. If they are arrays then the columns of x and y are treated separately and an area returned for each.
If the optional dim argument is given, then polyarea
works along this dimension of the arrays x and y.
An example of the use of polyarea might be
rand ("state", 2);
x = rand (10, 1);
y = rand (10, 1);
[c, f] = voronoin ([x, y]);
af = zeros (size (f));
for i = 1 : length (f)
af(i) = polyarea (c (f {i, :}, 1), c (f {i, :}, 2));
endfor
|
Facets of the Voronoi diagram with a vertex at infinity have infinity
area. A simplified version of polyarea for rectangles is
available with rectint
Compute the area of intersection of rectangles in a and rectangles in b. Rectangles are defined as [x y width height] where x and y are the minimum values of the two orthogonal dimensions.
If a or b are matrices, then the output, area, is a matrix where the i-th row corresponds to the i-th row of a and the j-th column corresponds to the j-th row of b.
See also: polyarea.
For a polygon defined by vertex points (xv, yv), determine
if the points (x, y) are inside or outside the polygon.
The variables x, y, must have the same dimension. The optional
output on gives the points that are on the polygon.
An example of the use of inpolygon might be
randn ("state", 2);
x = randn (100, 1);
y = randn (100, 1);
vx = cos (pi * [-1 : 0.1: 1]);
vy = sin (pi * [-1 : 0.1 : 1]);
in = inpolygon (x, y, vx, vy);
plot (vx, vy, x(in), y(in), "r+", x(!in), y(!in), "bo");
axis ([-2, 2, -2, 2]);
|
The result of which can be seen in fig:inpolygon.
Figure 30.4: Demonstration of the inpolygon function to determine the
points inside a polygon
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The convex hull of a set of points is the minimum convex envelope
containing all of the points. Octave has the functions convhull
and convhulln to calculate the convex hull of 2-dimensional and
N-dimensional sets of points.
Compute the convex hull of the set of points defined by the arrays x and y. The hull H is an index vector into the set of points and specifies which points form the enclosing hull.
An optional third argument, which must be a string or cell array of strings,
contains options passed to the underlying qhull command.
See the documentation for the Qhull library for details
http://www.qhull.org/html/qh-quick.htm#options.
The default option is {"Qt"}.
If options is not present or [] then the default arguments are
used. Otherwise, options replaces the default argument list.
To append user options to the defaults it is necessary to repeat the
default arguments in options. Use a null string to pass no arguments.
Compute the convex hull of the set of points pts which is a matrix of size [n, dim] containing n points in a space of dimension dim. The hull h is an index vector into the set of points and specifies which points form the enclosing hull.
An optional second argument, which must be a string or cell array of strings, contains options passed to the underlying qhull command. See the documentation for the Qhull library for details http://www.qhull.org/html/qh-quick.htm#options. The default options depend on the dimension of the input:
{"Qt"}
{"Qt", "Qx"}
If options is not present or [] then the default arguments are
used. Otherwise, options replaces the default argument list.
To append user options to the defaults it is necessary to repeat the
default arguments in options. Use a null string to pass no arguments.
If the second output v is requested the volume of the enclosing convex hull is calculated.
An example of the use of convhull is
x = -3:0.05:3; y = abs (sin (x)); k = convhull (x, y); plot (x(k), y(k), "r-", x, y, "b+"); axis ([-3.05, 3.05, -0.05, 1.05]); |
The output of the above can be seen in fig:convhull.
Figure 30.5: The convex hull of a simple set of points
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
An important use of the Delaunay tessellation is that it can be used to
interpolate from scattered data to an arbitrary set of points. To do
this the N-simplex of the known set of points is calculated with
delaunay, delaunay3 or delaunayn. Then the
simplices in to which the desired points are found are
identified. Finally the vertices of the simplices are used to
interpolate to the desired points. The functions that perform this
interpolation are griddata, griddata3 and
griddatan.
Generate a regular mesh from irregular data using interpolation.
The function is defined by z = f (x, y).
Inputs x, y, z are vectors of the same length
or x, y are vectors and z is matrix.
The interpolation points are all (xi, yi). If
xi, yi are vectors then they are made into a 2-D mesh.
The interpolation method can be "nearest", "cubic" or
"linear". If method is omitted it defaults to "linear".
Generate a regular mesh from irregular data using interpolation.
The function is defined by v = f (x, y, z).
The interpolation points are specified by xi, yi, zi.
The interpolation method can be "nearest" or "linear".
If method is omitted it defaults to "linear".
The optional argument options is passed directly to Qhull when
computing the Delaunay triangulation used for interpolation. See
delaunayn for information on the defaults and how to pass different
values.
Generate a regular mesh from irregular data using interpolation.
The function is defined by y = f (x).
The interpolation points are all xi.
The interpolation method can be "nearest" or "linear".
If method is omitted it defaults to "linear".
The optional argument options is passed directly to Qhull when
computing the Delaunay triangulation used for interpolation. See
delaunayn for information on the defaults and how to pass different
values.
An example of the use of the griddata function is
rand ("state", 1);
x = 2*rand (1000,1) - 1;
y = 2*rand (size (x)) - 1;
z = sin (2*(x.^2+y.^2));
[xx,yy] = meshgrid (linspace (-1,1,32));
griddata (x,y,z,xx,yy);
|
that interpolates from a random scattering of points, to a uniform grid. The output of the above can be seen in fig:griddata.
Figure 30.6: Interpolation from a scattered data to a regular grid
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This chapter describes the signal processing and fast Fourier transform functions available in Octave. Fast Fourier transforms are computed with the FFTW or FFTPACK libraries depending on how Octave is built.
Compute the discrete Fourier transform of A using a Fast Fourier Transform (FFT) algorithm.
The FFT is calculated along the first non-singleton dimension of the
array. Thus if x is a matrix, fft (x) computes the
FFT for each column of x.
If called with two arguments, n is expected to be an integer specifying the number of elements of x to use, or an empty matrix to specify that its value should be ignored. If n is larger than the dimension along which the FFT is calculated, then x is resized and padded with zeros. Otherwise, if n is smaller than the dimension along which the FFT is calculated, then x is truncated.
If called with three arguments, dim is an integer specifying the dimension of the matrix along which the FFT is performed
Compute the inverse discrete Fourier transform of A using a Fast Fourier Transform (FFT) algorithm.
The inverse FFT is calculated along the first non-singleton dimension
of the array. Thus if x is a matrix, fft (x) computes
the inverse FFT for each column of x.
If called with two arguments, n is expected to be an integer specifying the number of elements of x to use, or an empty matrix to specify that its value should be ignored. If n is larger than the dimension along which the inverse FFT is calculated, then x is resized and padded with zeros. Otherwise, if n is smaller than the dimension along which the inverse FFT is calculated, then x is truncated.
If called with three arguments, dim is an integer specifying the dimension of the matrix along which the inverse FFT is performed
Compute the two-dimensional discrete Fourier transform of A using a Fast Fourier Transform (FFT) algorithm.
The optional arguments m and n may be used specify the number of rows and columns of A to use. If either of these is larger than the size of A, A is resized and padded with zeros.
If A is a multi-dimensional matrix, each two-dimensional sub-matrix of A is treated separately.
See also: ifft2, fft, fftn, fftw.
Compute the inverse two-dimensional discrete Fourier transform of A using a Fast Fourier Transform (FFT) algorithm.
The optional arguments m and n may be used specify the number of rows and columns of A to use. If either of these is larger than the size of A, A is resized and padded with zeros.
If A is a multi-dimensional matrix, each two-dimensional sub-matrix of A is treated separately
See also: fft2, ifft, ifftn, fftw.
Compute the N-dimensional discrete Fourier transform of A using a Fast Fourier Transform (FFT) algorithm.
The optional vector argument size may be used specify the dimensions of the array to be used. If an element of size is smaller than the corresponding dimension of A, then the dimension of A is truncated prior to performing the FFT. Otherwise, if an element of size is larger than the corresponding dimension then A is resized and padded with zeros.
Compute the inverse N-dimensional discrete Fourier transform of A using a Fast Fourier Transform (FFT) algorithm.
The optional vector argument size may be used specify the dimensions of the array to be used. If an element of size is smaller than the corresponding dimension of A, then the dimension of A is truncated prior to performing the inverse FFT. Otherwise, if an element of size is larger than the corresponding dimension then A is resized and padded with zeros.
Octave uses the FFTW libraries to perform FFT computations. When Octave starts up and initializes the FFTW libraries, they read a system wide file (on a Unix system, it is typically ‘/etc/fftw/wisdom’) that contains information useful to speed up FFT computations. This information is called the wisdom. The system-wide file allows wisdom to be shared between all applications using the FFTW libraries.
Use the fftw function to generate and save wisdom. Using the
utilities provided together with the FFTW libraries
(fftw-wisdom on Unix systems), you can even add wisdom
generated by Octave to the system-wide wisdom file.
Manage FFTW wisdom data. Wisdom data can be used to significantly
accelerate the calculation of the FFTs, but implies an initial cost
in its calculation. When the FFTW libraries are initialized, they read
a system wide wisdom file (typically in ‘/etc/fftw/wisdom’), allowing
wisdom to be shared between applications other than Octave. Alternatively,
the fftw function can be used to import wisdom. For example,
wisdom = fftw ("dwisdom")
|
will save the existing wisdom used by Octave to the string wisdom.
This string can then be saved to a file and restored using the save
and load commands respectively. This existing wisdom can be
re-imported as follows
fftw ("dwisdom", wisdom)
|
If wisdom is an empty string, then the wisdom used is cleared.
During the calculation of Fourier transforms further wisdom is generated.
The fashion in which this wisdom is generated is also controlled by
the fftw function. There are five different manners in which the
wisdom can be treated:
"estimate"Specifies that no run-time measurement of the optimal means of calculating a particular is performed, and a simple heuristic is used to pick a (probably sub-optimal) plan. The advantage of this method is that there is little or no overhead in the generation of the plan, which is appropriate for a Fourier transform that will be calculated once.
"measure"In this case a range of algorithms to perform the transform is considered and the best is selected based on their execution time.
"patient"Similar to "measure", but a wider range of algorithms is
considered.
"exhaustive"Like "measure", but all possible algorithms that may be used to
treat the transform are considered.
"hybrid"As run-time measurement of the algorithm can be expensive, this is a
compromise where "measure" is used for transforms up to the size
of 8192 and beyond that the "estimate" method is used.
The default method is "estimate". The current method can
be queried with
method = fftw ("planner")
|
or set by using
fftw ("planner", method)
|
Note that calculated wisdom will be lost when restarting Octave. However, the wisdom data can be reloaded if it is saved to a file as described above. Saved wisdom files should not be used on different platforms since they will not be efficient and the point of calculating the wisdom is lost.
The number of threads used for computing the plans and executing the transforms can be set with
fftw ("threads", NTHREADS)
|
Note that octave must be compiled with multi-threaded FFTW support for this feature. The number of processors available to the current process is used per default.
Convolve two vectors using the FFT for computation.
c = fftconv (x, y) returns a vector of length equal to
length (x) + length (y) - 1.
If x and y are the coefficient vectors of two polynomials, the
returned value is the coefficient vector of the product polynomial.
The computation uses the FFT by calling the function fftfilt. If
the optional argument n is specified, an N-point FFT is used.
With two arguments, fftfilt filters x with the FIR filter
b using the FFT.
Given the optional third argument, n, fftfilt uses the
overlap-add method to filter x with b using an N-point
FFT. The FFT size must be an even power of 2 and must be greater than
or equal to the length of b. If the specified n does not
meet these criteria, it is automatically adjusted to the nearest value
that does.
If x is a matrix, filter each column of the matrix.
Return the solution to the following linear, time-invariant difference equation:
N M SUM a(k+1) y(n-k) = SUM b(k+1) x(n-k) for 1<=n<=length(x) k=0 k=0 |
where N=length(a)-1 and M=length(b)-1. The result is calculated over the first non-singleton dimension of x or over dim if supplied.
An equivalent form of the equation is:
N M
y(n) = - SUM c(k+1) y(n-k) + SUM d(k+1) x(n-k) for 1<=n<=length(x)
k=1 k=0
|
where c = a/a(1) and d = b/a(1).
If the fourth argument si is provided, it is taken as the initial state of the system and the final state is returned as sf. The state vector is a column vector whose length is equal to the length of the longest coefficient vector minus one. If si is not supplied, the initial state vector is set to all zeros.
In terms of the Z Transform, y is the result of passing the discrete- time signal x through a system characterized by the following rational system function:
M
SUM d(k+1) z^(-k)
k=0
H(z) = ---------------------
N
1 + SUM c(k+1) z^(-k)
k=1
|
Apply the 2-D FIR filter b to x. If the argument shape is specified, return an array of the desired shape. Possible values are:
"full"pad x with zeros on all sides before filtering.
"same"unpadded x (default)
"valid"trim x after filtering so edge effects are no included.
Note this is just a variation on convolution, with the parameters reversed and b rotated 180 degrees.
See also: conv2.
Return the complex frequency response h of the rational IIR filter whose numerator and denominator coefficients are b and a, respectively. The response is evaluated at n angular frequencies between 0 and 2*pi.
The output value w is a vector of the frequencies.
If a is omitted, the denominator is assumed to be 1 (this corresponds to a simple FIR filter).
If n is omitted, a value of 512 is assumed. For fastest computation, n should factor into a small number of small primes.
If the fourth argument, "whole", is omitted the response is
evaluated at frequencies between 0 and
pi.
freqz (b, a, w)
Evaluate the response at the specific frequencies in the vector w. The values for w are measured in radians.
[…] = freqz (…, Fs)
Return frequencies in Hz instead of radians assuming a sampling rate Fs. If you are evaluating the response at specific frequencies w, those frequencies should be requested in Hz rather than radians.
freqz (…)
Plot the magnitude and phase response of h rather than returning them.
See also: freqz_plot.
Plot the magnitude and phase response of h.
If the optional freq_norm argument is true, the frequency vector w is in units of normalized radians. If freq_norm is false, or not given, then w is measured in Hertz.
See also: freqz.
Return sin (pi*x) / (pi*x).
Unwrap radian phases by adding multiples of 2*pi as appropriate to remove jumps greater than tol. tol defaults to pi.
Unwrap will work along the dimension dim. If dim is unspecified it defaults to the first non-singleton dimension.
Fit an ARCH regression model to the time series y using the scoring algorithm in Engle’s original ARCH paper. The model is
y(t) = b(1) * x(t,1) + … + b(k) * x(t,k) + e(t), h(t) = a(1) + a(2) * e(t-1)^2 + … + a(p+1) * e(t-p)^2 |
in which e(t) is N(0, h(t)), given a time-series vector y up to time t-1 and a matrix of (ordinary) regressors x up to t. The order of the regression of the residual variance is specified by p.
If invoked as arch_fit (y, k, p) with a
positive integer k, fit an ARCH(k, p) process,
i.e., do the above with the t-th row of x given by
[1, y(t-1), …, y(t-k)] |
Optionally, one can specify the number of iterations iter, the updating factor gamma, and initial values a0 and b0 for the scoring algorithm.
Simulate an ARCH sequence of length t with AR coefficients b and CH coefficients a. I.e., the result y(t) follows the model
y(t) = b(1) + b(2) * y(t-1) + … + b(lb) * y(t-lb+1) + e(t), |
where e(t), given y up to time t-1, is N(0, h(t)), with
h(t) = a(1) + a(2) * e(t-1)^2 + … + a(la) * e(t-la+1)^2 |
For a linear regression model
y = x * b + e |
perform a Lagrange Multiplier (LM) test of the null hypothesis of no conditional heteroscedascity against the alternative of CH(p).
I.e., the model is
y(t) = b(1) * x(t,1) + … + b(k) * x(t,k) + e(t), |
given y up to t-1 and x up to t, e(t) is N(0, h(t)) with
h(t) = v + a(1) * e(t-1)^2 + … + a(p) * e(t-p)^2, |
and the null is a(1) == … == a(p) == 0.
If the second argument is a scalar integer, k, perform the same test in a linear autoregression model of order k, i.e., with
[1, y(t-1), …, y(t-k)] |
as the t-th row of x.
Under the null, LM approximately has a chisquare distribution with p degrees of freedom and pval is the p-value (1 minus the CDF of this distribution at LM) of the test.
If no output argument is given, the p-value is displayed.
Return a simulation of the ARMA model
x(n) = a(1) * x(n-1) + … + a(k) * x(n-k)
+ e(n) + b(1) * e(n-1) + … + b(l) * e(n-l)
|
in which k is the length of vector a, l is the length of vector b and e is Gaussian white noise with variance v. The function returns a vector of length t.
The optional parameter n gives the number of dummy x(i) used for initialization, i.e., a sequence of length t+n is generated and x(n+1:t+n) is returned. If n is omitted, n = 100 is used.
Given a time series (vector) y, return a matrix with ones in the
first column and the first k lagged values of y in the
other columns. I.e., for t > k, [1,
y(t-1), …, y(t-k)] is the t-th row
of the result. The resulting matrix may be used as a regressor matrix
in autoregressions.
Return the filter coefficients of a Bartlett (triangular) window of length m.
For a definition of the Bartlett window, see e.g., A. V. Oppenheim & R. W. Schafer, Discrete-Time Signal Processing.
Return the filter coefficients of a Blackman window of length m.
For a definition of the Blackman window, see e.g., A. V. Oppenheim & R. W. Schafer, Discrete-Time Signal Processing.
If x is a vector, detrend (x, p) removes the
best fit of a polynomial of order p from the data x.
If x is a matrix, detrend (x, p) does the same
for each column in x.
The second argument is optional. If it is not specified, a value of 1 is assumed. This corresponds to removing a linear trend.
The order of the polynomial can also be given as a string, in which case
p must be either "constant" (corresponds to
p=0) or
"linear" (corresponds to p=1).
See also: polyfit.
Return the estimator d for the differencing parameter of an integrated time series.
The frequencies from [2*pi*a/t, 2*pi*b/T] are used for the estimation. If b is omitted, the interval [2*pi/T, 2*pi*a/T] is used. If both b and a are omitted then a = 0.5 * sqrt (T) and b = 1.5 * sqrt (T) is used, where T is the sample size. If x is a matrix, the differencing parameter of each column is estimated.
The estimators for all frequencies in the intervals described above is returned in dd. The value of d is simply the mean of dd.
Reference: P.J. Brockwell & R.A. Davis. Time Series: Theory and Methods. Springer 1987.
Perform one step of the Durbin-Levinson algorithm.
The vector c specifies the autocovariances [gamma_0, …,
gamma_t] from lag 0 to t, oldphi specifies the
coefficients based on c(t-1) and oldv specifies the
corresponding error.
If oldphi and oldv are omitted, all steps from 1 to t of the algorithm are performed.
Perform a shift of the vector x, for use with the fft
and ifft functions, in order the move the frequency 0 to the
center of the vector or matrix.
If x is a vector of N elements corresponding to N
time samples spaced by dt, then
fftshift (fft (x)) corresponds to frequencies
f = [ -(ceil((N-1)/2):-1:1)*df 0 (1:floor((N-1)/2))*df ] |
where df = 1 / dt.
If x is a matrix, the same holds for rows and columns. If x is an array, then the same holds along each dimension.
The optional dim argument can be used to limit the dimension along which the permutation occurs.
Undo the action of the fftshift function. For even length
x, fftshift is its own inverse, but odd lengths differ
slightly.
Compute the fractional differences (1-L)^d x where L denotes the lag-operator and d is greater than -1.
Return the filter coefficients of a Hamming window of length m.
For a definition of the Hamming window, see e.g., A. V. Oppenheim & R. W. Schafer, Discrete-Time Signal Processing.
Return the filter coefficients of a Hanning window of length m.
For a definition of this window type, see e.g., A. V. Oppenheim & R. W. Schafer, Discrete-Time Signal Processing.
Estimate the Hurst parameter of sample x via the rescaled range statistic. If x is a matrix, the parameter is estimated for every single column.
Return the Piecewise Cubic Hermite Interpolating Polynomial (pchip) of points x and y.
If called with two arguments, return the piecewise polynomial pp
that may be used with ppval to evaluate the polynomial at specific
points. When called with a third input argument, pchip evaluates
the pchip polynomial at the points xi. The third calling form is
equivalent to ppval (pchip (x, y), xi).
The variable x must be a strictly monotonic vector (either
increasing or decreasing) of length n. y can be either a
vector or array. If y is a vector then it must be the same length
n as x. If y is an array then the size of y must
have the form
[s1, s2, …, sk, n]
The array is reshaped internally to a matrix where the leading
dimension is given by
s1 * s2 * … * sk
and each row of this matrix is then treated separately. Note that this
is exactly opposite to interp1 but is done for MATLAB
compatibility.
For a data matrix x from a sample of size n, return the periodogram. The angular frequency is returned in w.
[Pxx,w] = periodogram (x).
[Pxx,w] = periodogram (x,win).
[Pxx,w] = periodogram (x,win,nfft).
[Pxx,f] = periodogram (x,win,nfft,Fs).
[Pxx,f] = periodogram (x,win,nfft,Fs,"range").
"twosided", the full
spectrum is estimated.
"onesided" computes spectrum from [0..nfft/2+1].
"twosided" computes spectrum from [0..nfft-1]. These
strings can appear at any position in the list input arguments after
window.
Return a sinetone of frequency freq with length of sec seconds at sampling rate rate and with amplitude ampl. The arguments freq and ampl may be vectors of common size.
Defaults are rate = 8000, sec = 1 and ampl = 64.
Return an m-element vector with i-th element given by
sin (2 * pi * (i+d-1) / n).
The default value for d is 0 and the default value for n is m.
Return the spectral density estimator given a vector of autocovariances c, window name win, and bandwidth, b.
The window name, e.g., "triangle" or "rectangle" is
used to search for a function called win_lw.
If win is omitted, the triangle window is used. If b is
omitted, 1 / sqrt (length (x)) is used.
See also: spectral_xdf.
Return the spectral density estimator given a data vector x, window name win, and bandwidth, b.
The window name, e.g., "triangle" or "rectangle" is
used to search for a function called win_sw.
If win is omitted, the triangle window is used. If b is
omitted, 1 / sqrt (length (x)) is used.
See also: spectral_adf.
Return Spencer’s 15 point moving average of each column of x.
Compute the short-time Fourier transform of the vector x with num_coef coefficients by applying a window of win_size data points and an increment of inc points.
Before computing the Fourier transform, one of the following windows is applied:
"hanning"win_type = 1
"hamming"win_type = 2
"rectangle"win_type = 3
The window names can be passed as strings or by the win_type number.
The following defaults are used for unspecified arguments: win_size = 80, inc = 24, num_coef = 64, and win_type = 1.
y = stft (x, …) returns the absolute values
of the Fourier coefficients according to the num_coef positive
frequencies.
[y, c] = stft ( returns the
entire STFT-matrix y and a 3-element vector c containing
the window size, increment, and window type, which is needed by the
x, …)synthesis function.
See also: synthesis.
Compute a signal from its short-time Fourier transform y and a 3-element vector c specifying window size, increment, and window type.
The values y and c can be derived by
[y, c] = stft (x , …) |
See also: stft.
Fit an AR (p)-model with Yule-Walker estimates given a vector c
of autocovariances [gamma_0, …, gamma_p].
Returns the AR coefficients, a, and the variance of white noise, v.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Since an image is basically a matrix, Octave is a very powerful environment for processing and analyzing images. To illustrate how easy it is to do image processing in Octave, the following example will load an image, smooth it by a 5-by-5 averaging filter, and compute the gradient of the smoothed image.
I = imread ("myimage.jpg");
S = conv2 (I, ones (5, 5) / 25, "same");
[Dx, Dy] = gradient (S);
|
In this example S contains the smoothed image, and Dx
and Dy contains the partial spatial derivatives of the image.
| 32.1 Loading and Saving Images | ||
| 32.2 Displaying Images | ||
| 32.3 Representing Images | ||
| 32.4 Plotting on top of Images | ||
| 32.5 Color Conversion |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The first step in most image processing tasks is to load an image
into Octave which is done with the imread function.
The imwrite function is the corresponding function
for writing images to the disk.
In summary, most image processing code will follow the structure of this code
I = imread ("my_input_image.img");
J = process_my_image (I);
imwrite (J, "my_output_image.img");
|
Read images from various file formats.
Reads an image as a matrix from the file filename. If there is no file filename, and ext was specified, it will look for a file named filename and extension ext, i.e., a file named filename.ext.
The size and class of the output depends on the format of the image. A color image is returned as an MxNx3 matrix. Gray-level and black-and-white images are of size MxN. Multipage images will have an additional 4th dimension.
The bit depth of the image determines the
class of the output: "uint8", "uint16" or "single"
for gray and color, and "logical" for black and white.
Note that indexed images always return the indexes for a colormap,
independent if map is a requested output. To obtain the actual
RGB image, use ind2rgb. When more than one indexed image is being
read, map is obtained from the first. In some rare cases this
may be incorrect and imfinfo can be used to obtain the colormap of
each image.
See the Octave manual for more information in representing images.
Some file formats, such as TIFF and GIF, are able to store multiple images in a single file. idx can be a scalar or vector specifying the index of the images to read. By default, Octave will only read the first page.
Depending on the file format, it is possible to configure the reading of images with param, val pairs. The following options are supported:
"Frames" or "Index"’This is an alternative method to specify idx. When specifying it
in this way, its value can also be the string "all".
"Info"’This option exists for MATLAB compatibility and has no effect. For maximum performance while reading multiple images from a single file, use the Index option.
"PixelRegion"’Controls the image region that is read. Takes as value a cell array
with two arrays of 3 elements {rows cols}. The
elements in the array are the start, increment and end pixel to be
read. If the increment value is omitted, defaults to 1.
Write images in various file formats.
The image img can be a binary, grayscale, RGB, or multi-dimensional
image. The size and class of img should be the same as what should
be expected when reading it with imread: the 3rd and 4th dimensions
reserved for color space, and multiple pages respectively. If it’s an
indexed image, the colormap map must also be specified.
If ext is not supplied, the file extension of filename is used
to determine the format. The actual supported formats are dependent on
options made during the build of Octave. Use imformats to check
the support of the different image formats.
Depending on the file format, it is possible to configure the writing of images with param, val pairs. The following options are supported:
Alpha (transparency) channel for the image. This must be a matrix with same class, and number of rows and columns of img. In case of a multipage image, the size of the 4th dimension must also match and the third dimension must be a singleton. By default, image will be completely opaque.
For formats that accept animations (such as GIF), controls for how long a frame is displayed until it moves to the next one. The value must be scalar (which will applied to all frames in img), or a vector of length equal to the number of frames in im. The value is in seconds, must be between 0 and 655.35, and defaults to 0.5.
For formats that accept animations (such as GIF), controls what happens to a frame before drawing the next one. Its value can be one of the following strings: "doNotSpecify" (default); "leaveInPlace"; "restoreBG"; and "restorePrevious", or a cell array of those string with length equal to the number of frames in img.
For formats that accept animations (such as GIF), controls how many times the sequence is repeated. A value of Inf means an infinite loop (default), a value of 0 or 1 that the sequence is played only once (loops zero times), while a value of 2 or above loops that number of times (looping twice means it plays the complete sequence 3 times). This option is ignored when there is only a single image at the end of writing the file.
Set the quality of the compression. The value should be an integer between 0 and 100, with larger values indicating higher visual quality and lower compression. Defaults to 75.
Some file formats, such as TIFF and GIF, are able to store multiple
images in a single file. This option specifies if img should be
appended to the file (if it exists) or if a new file should be created
for it (possibly overwriting an existing file). The value should be
the string "Overwrite" (default), or "Append".
Despite this option, the most efficient method of writing a multipage
image is to pass a 4 dimensional img to imwrite, the
same matrix that could be expected when using imread with the
option "Index" set to "all".
Query or set the internal variable that specifies a colon separated list of directories in which to search for image files.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: EXEC_PATH, OCTAVE_HOME.
It is possible to get information about an image file on disk, without actually
reading it into Octave. This is done using the imfinfo function which
provides read access to many of the parameters stored in the header of the image
file.
Read image information from a file.
imfinfo returns a structure containing information about the image
stored in the file filename. If there is no file filename,
and ext was specified, it will look for a file named filename
and extension ext, i.e., a file named filename.ext.
The output structure info contains the following fields:
The full name of the image file.
Date of last modification to the file.
Number of bytes of the image on disk
Image format (e.g., "jpeg").
Image height in pixels.
Image Width in pixels.
Number of bits per channel per pixel.
Image type. Value is "grayscale", "indexed",
"truecolor", "CMYK", or "undefined".
X resolution of the image.
Y resolution of the image.
Units of image resolution. Value is "Inch",
"Centimeter", or "undefined".
Time in 1/100ths of a second (0 to 65535) which must expire before displaying the next image in an animated sequence.
Number of iterations to loop an animation.
Endian option for formats that support it. Value is "little-endian",
"big-endian", or "undefined".
Gamma level of the image. The same color image displayed on two different workstations may look different due to differences in the display monitor.
JPEG/MIFF/PNG compression level. Value is an integer in the range [0 100].
Only valid for GIF images, control how successive frames are rendered (how
the preceding frame is disposed of) when creating a GIF animation. Values
can be "doNotSpecify", "leaveInPlace", "restoreBG",
or "restorePrevious". For non-GIF files, value is an empty string.
Value is a 1x8 Matrix with the x,y chromaticity values for white, red, green, and blue points, in that order.
Image comment.
Compression type. Value can be "none", "bzip",
"fax3", "fax4", "jpeg", "lzw",
"rle", "deflate", "lzma", "jpeg2000",
"jbig2", "jbig2", or "undefined".
Colormap for each image.
The orientation of the image with respect to the rows and columns. Value is an integer between 1 and 8 as defined in the TIFF 6 specifications, and for MATLAB compatibility.
Name and version of the software or firmware of the camera or image input device used to generate the image.
The manufacturer of the recording equipment. This is the manufacture of the DSC, scanner, video digitizer or other equipment that generated the image.
The model name or model number of the recording equipment as mentioned
on the field "Make".
The date and time of image creation as defined by the Exif standard, i.e., it is the date and time the file was changed.
The title of the image as defined by the Exif standard.
Name of the camera owner, photographer or image creator.
Copyright notice of the person or organization claiming rights to the image.
A struct with information retrieved from the Exif tag.
A struct with geotagging information retrieved from the Exif tag.
By default, Octave’s image IO functions (imread, imwrite,
and imfinfo) use the GraphicsMagick library for their
operations. This means a vast number of image formats is supported
but considering the large amount of image formats in science and
its commonly closed nature, it is impossible to have a library
capable of reading them all. Because of this, the function
imformats keeps a configurable list of available formats,
their extensions, and what functions should the image IO functions
use. This allows to expand Octave’s image IO capabilities by
creating functions aimed at acting on specific file formats.
While it would be possible to call the extra functions directly,
properly configuring Octave with imformats allows to keep a
consistent code that is abstracted from file formats.
It is important to note that a file format is not actually defined by its
file extension and that GraphicsMagick is capable to read and write
more file formats than the ones listed by imformats. What this
means is that even with an incorrect or missing extension the image may
still be read correctly, and that even unlisted formats are not necessarily
unsupported.
Manage supported image formats.
formats is a structure with information about each supported file
format, or from a specific format ext, the value displayed on the
field ext. It contains the following fields:
The name of the file format. This may match the file extension but Octave will automatically detect the file format.
A long description of the file format.
A function handle to confirm if a file is of the specified format.
A function handle to write if a file is of the specified format.
A function handle to open files the specified format.
A function handle to obtain image information of the specified format.
Logical value if format supports alpha channel (transparency or matte).
Logical value if format supports multipage (multiple images per file).
It is possible to change the way Octave manages file formats with the options
"add", "remove", and "update", and supplying a
structure format with the required fields. The option
"factory" resets the configuration to the default.
This can be used by Octave packages to extend the image reading capabilities Octave, through use of the PKG_ADD and PKG_DEL commands.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A natural part of image processing is visualization of an image.
The most basic function for this is the imshow function that
shows the image given in the first input argument.
Display the image im, where im can be a 2-dimensional (grayscale image) or a 3-dimensional (RGB image) matrix.
If limits is a 2-element vector [low, high],
the image is shown using a display range between low and
high. If an empty matrix is passed for limits, the
display range is computed as the range between the minimal and the
maximal value in the image.
If map is a valid color map, the image will be shown as an indexed image using the supplied color map.
If a file name is given instead of an image, the file will be read and shown.
If given, the parameter string_param1 has value value1. string_param1 can be any of the following:
"displayrange"value1 is the display range as described above.
"xdata"If value1 is a two element vector, it must contain horizontal axis limits in the form [xmin xmax]; Otherwise value1 must be a vector and only the first and last elements will be used for xmin and xmax respectively.
"ydata"If value1 is a two element vector, it must contain vertical axis limits in the form [ymin ymax]; Otherwise value1 must be a vector and only the first and last elements will be used for ymin and ymax respectively.
The optional return value h is a graphics handle to the image.
Display a matrix as an indexed color image.
The elements of img are indices into the current colormap.
x and y are optional 2-element vectors, [min, max],
which specify the range for the axis labels. If a range is specified as
[max, min] then the image will be reversed along that axis. For
convenience, x and y may be specified as N-element vectors
matching the length of the data in img. However, only the first and
last elements will be used to determine the axis limits.
Warning: x and y are ignored when using gnuplot 4.0
or earlier.
Multiple property/value pairs may be specified for the image object, but they must appear in pairs.
The optional return value h is a graphics handle to the image.
Implementation Note: The origin (0, 0) for images is located in the
upper left. For ordinary plots, the origin is located in the lower
left. Octave handles this inversion by plotting the data normally,
and then reversing the direction of the y-axis by setting the
ydir property to "reverse". This has implications whenever
an image and an ordinary plot need to be overlaid. The recommended
solution is to display the image and then plot the reversed ydata
using, for example, flipud (ydata).
Calling Forms: The image function can be called in two forms:
High-Level and Low-Level. When invoked with normal options, the High-Level
form is used which first calls newplot to prepare the graphic figure
and axes. When the only inputs to image are property/value pairs
the Low-Level form is used which creates a new instance of an image object
and inserts it in the current axes.
Display a scaled version of the matrix img as a color image. The
colormap is scaled so that the entries of the matrix occupy the entire
colormap. If climits = [lo, hi] is given, then that
range is set to the "clim" of the current axes.
The axis values corresponding to the matrix elements are specified in x and y, either as pairs giving the minimum and maximum values for the respective axes, or as values for each row and column of the matrix img.
The optional return value h is a graphics handle to the image.
Calling Forms: The imagesc function can be called in two forms:
High-Level and Low-Level. When invoked with normal options, the High-Level
form is used which first calls newplot to prepare the graphic figure
and axes. When the only inputs to image are property/value pairs
the Low-Level form is used which creates a new instance of an image object
and inserts it in the current axes.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In general Octave supports four different kinds of images, grayscale images, RGB images, binary images, and indexed images. A grayscale image is represented with an M-by-N matrix in which each element corresponds to the intensity of a pixel. An RGB image is represented with an M-by-N-by-3 array where each 3-vector corresponds to the red, green, and blue intensities of each pixel.
The actual meaning of the value of a pixel in a grayscale or RGB
image depends on the class of the matrix. If the matrix is of class
double pixel intensities are between 0 and 1, if it is of class
uint8 intensities are between 0 and 255, and if it is of class
uint16 intensities are between 0 and 65535.
A binary image is an M-by-N matrix of class logical.
A pixel in a binary image is black if it is false and white
if it is true.
An indexed image consists of an M-by-N matrix of integers
and a C-by-3 color map. Each integer corresponds to an
index in the color map, and each row in the color map corresponds to
an RGB color. The color map must be of class double with values
between 0 and 1.
Return true if cmap is a colormap.
A colormap is a real matrix with n rows and 3 columns. Each row represents a single color. The columns contain red, green, and blue intensities respectively. All entries must be between 0 and 1 inclusive.
Convert a grayscale or binary intensity image to an indexed image.
The indexed image will consist of n different intensity values. If not given n defaults to 64 for grayscale images or 2 for binary black and white images.
The output img is of class uint8 if n is less than or equal to 256; Otherwise the return class is uint16.
Convert a color indexed image to a grayscale intensity image.
The image x must be an indexed image which will be converted using the colormap cmap. If cmap does not contain enough colors for the image, pixels in x outside the range are mapped to the last color in the map before conversion to grayscale.
The output I is of the same class as the input x and may be
one of uint8, uint16, single, or double.
Implementation Note: There are several ways of converting colors to
grayscale intensities. This functions uses the luminance value obtained
from rgb2ntsc which is I = 0.299*R + 0.587*G + 0.114*B.
Other possibilities include the value component from rgb2hsv or
using a single color channel from ind2rgb.
Convert an image in red-green-blue (RGB) color space to an indexed image.
The input image rgb can be specified as a single matrix of size MxNx3, or as three separate variables, R, G, and B, its three colour channels, red, green, and blue.
It outputs an indexed image x and a colormap map to interpret an image exactly the same as the input. No dithering or other form of color quantization is performed. The output class of the indexed image x can be uint8, uint16 or double, whichever is required to specify the number of unique colors in the image (which will be equal to the number of rows in map) in order
Multi-dimensional indexed images (of size MxNx3xK) are also supported, both via a single input (rgb) or its three colour channels as separate variables.
Convert an indexed image to red, green, and blue color components.
The image x must be an indexed image which will be converted using the colormap map. If map does not contain enough colors for the image, pixels in x outside the range are mapped to the last color in the map.
The output may be a single RGB image (MxNx3 matrix where M and N are the original image x dimensions, one for each of the red, green and blue channels). Alternatively, the individual red, green, and blue color matrices of size MxN may be returned.
Multi-dimensional indexed images (of size MxNx1xK) are also supported.
Query or set the current colormap.
With no input arguments, colormap returns the current color map.
colormap (map) sets the current colormap to map. The
colormap should be an n row by 3 column matrix. The columns
contain red, green, and blue intensities respectively. All entries
must be between 0 and 1 inclusive. The new colormap is returned.
colormap ("default") restores the default colormap (the
jet map with 64 entries). The default colormap is returned.
The map may also be specified by a string, "map_name", where
map_name is the name of a function that returns a colormap.
If the first argument hax is an axes handle, then the colormap for the parent figure of hax is queried or set.
For convenience, it is also possible to use this function with the
command form, colormap map_name.
colormap ("list") returns a cell array with all of the available
colormaps. The options "register" and "unregister"
add or remove the colormap name from this list.
See also: jet.
Plot the components of a colormap.
Two different styles are available for displaying the cmap:
Plot the RGB line profile of the colormap for each of the channels (red, green and blue) with the plot lines colored appropriately. Each line represents the intensity of each RGB components across the colormap.
Draw the colormap across the X-axis so that the actual index colors are visible rather than the individual color components.
The optional return value h is a graphics handle to the created plot.
Run demo rgbplot to see an example of rgbplot and each style
option.
See also: colormap.
Create color colormap. This colormap ranges from red through orange to yellow. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap varies from black to white with gray-blue shades. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap is composed of as many equally spaced colors (not grays) in the RGB color space as possible. If there are not a perfect number n of regularly spaced colors then the remaining entries in the colormap are gradients of pure red, green, blue, and gray. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. The colormap varies from cyan to magenta. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap varies from black to a light copper tone. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap cycles through red, white, blue, and black with each index change. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create gray colormap. This colormap varies from black to white with shades of gray. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap ranges from black through dark red, red, orange, yellow, to white. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap begins with red, changes through
yellow, green, cyan, blue, and magenta, before returning to red.
It is useful for displaying periodic functions. The map is obtained by
linearly varying the hue through all possible values while keeping constant
maximum saturation and value. The equivalent code is
hsv2rgb ([(0:N-1)'/N, ones(N,2)]).
The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap ranges from dark blue through blue, cyan, green, yellow, red, to dark red. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap is composed of the list of colors
in the current axes "ColorOrder" property. The default is blue,
green, red, cyan, pink, yellow, and gray.
The argument n must be a scalar.
If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap varies from black to white with shades of blue. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap varies from black to white with shades of gray-pink. It gives a sepia tone when used on grayscale images. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap cycles through red, orange, yellow, green, blue and violet with each index change. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap ranges from red through orange, yellow, green, blue, to violet. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap varies from magenta to yellow. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap varies from green to yellow. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Create color colormap. This colormap is completely white. The argument n should be a scalar. If it is omitted, the length of the current colormap or 64 is assumed.
See also: colormap.
Create color colormap. This colormap varies from blue to green. The argument n must be a scalar. If unspecified, the length of the current colormap, or 64, is used.
See also: colormap.
Return a gray colormap that maximizes the contrast in an image. The returned colormap will have n rows. If n is not defined then the size of the current colormap is used.
An additional colormap is gmap40. This code map contains only
colors with integer values of the red, green and blue components. This
is a workaround for a limitation of gnuplot 4.0, that does not allow the color
of line or patch objects to be set. gmap40 is chiefly useful to gnuplot
4.0 users, and particularly in conjunction with the bar, surf,
and contour functions.
Create color colormap. The colormap consists of red, green, blue, yellow, magenta and cyan. This colormap is specifically designed for users of gnuplot 4.0 where these 6 colors are the allowable ones for patch objects. The argument n must be a scalar. If unspecified, a length of 6 is assumed. Larger values of n result in a repetition of the above colors.
See also: colormap.
The following three functions modify the existing colormap rather than replace it.
Brighten or darken a colormap. If the map argument is omitted, the
function is applied to the current colormap. The first argument can also be
a valid graphics handle h, in which case brighten is applied to
the colormap associated with this handle.
The argument beta must be a scalar between -1 and 1, where a negative value darkens and a positive value brightens the colormap.
If no output is specified then the result is written to the current colormap.
Cycle the colormap for t seconds with a color increment of inc.
Both parameters are optional. The default cycle time is 5 seconds and the
default increment is 2. If the option "inf" is given then cycle
continuously until Control-C is pressed.
When rotating the original color 1 becomes color 2, color 2 becomes color 3, etc. A positive or negative increment is allowed and a higher value of inc will cause faster cycling through the colormap.
See also: colormap.
Invert the colors in the current color scheme.
The root properties are also inverted such that all subsequent plot use the new color scheme.
If the optional argument color is present then the background color
is set to color rather than inverted. color may be a string
representing one of the eight known colors or an RGB triplet. The special
string argument "none" restores the plot to the default colors.
If the first argument hfig is a figure handle, then operate on
this figure rather than the current figure returned by gcf. The
root properties will not be changed.
The following functions can be used to manipulate colormaps.
Convert an input image X to an ouput indexed image Y which uses the smallest colormap possible newmap.
When the input is an indexed image (X with colormap map) the output is a colormap newmap from which any repeated rows have been eliminated. The output image, Y, is the original input image with the indices adjusted to match the new, possibly smaller, colormap.
When the input is an RGB image (an MxNx3 array), the output colormap will contain one entry for every unique color in the original image. In the worst case the new map could have as many rows as the number of pixels in the original image.
When the input is a grayscale image I, the output colormap will contain one entry for every unique intensity value in the original image. In the worst case the new map could have as many rows as the number of pixels in the original image.
Implementation Details:
newmap is always an Mx3 matrix, even if the input image is an intensity grayscale image I (all three RGB planes are assigned the same value).
The output image is of class uint8 if the size of the new colormap is less than or equal to 256. Otherwise, the output image is of class double.
Reorder colors in a colormap.
When called with only two arguments, cmpermute randomly rearranges
the colormap map and returns a new colormap newmap. It also
returns the indexed image Y which is the equivalent of the original
input image X when displayed using newmap.
When called with an optional third argument the order of colors in the new colormap is defined by index.
Caution: index should not have repeated elements or the
function will fail.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
If gnuplot is being used to display images it is possible to plot on
top of images. Since an image is a matrix it is indexed by row and
column values. The plotting system is, however, based on the
traditional (x, y) system. To minimize the difference between
the two systems Octave places the origin of the coordinate system in
the point corresponding to the pixel at (1, 1). So, to plot
points given by row and column values on top of an image, one should
simply call plot with the column values as the first argument
and the row values as the second. As an example the following code
generates an image with random intensities between 0 and 1, and shows
the image with red circles over pixels with an intensity above
0.99.
I = rand (100, 100);
[row, col] = find (I > 0.99);
hold ("on");
imshow (I);
plot (col, row, "ro");
hold ("off");
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave supports conversion from the RGB color system to NTSC and HSV and vice versa.
Transform a colormap or image from red-green-blue (RGB) space to hue-saturation-value (HSV) space.
A color in the RGB space consists of red, green, and blue intensities.
A color in HSV space is represented by hue, saturation, and value (brightness) levels. Value gives the amount of light in the color. Hue describes the dominant wavelength. Saturation is the amount of hue mixed into the color.
Transform a colormap or image from hue-saturation-value (HSV) space to red-green-blue (RGB) space.
A color in HSV space is represented by hue, saturation and value (brightness) levels. Value gives the amount of light in the color. Hue describes the dominant wavelength. Saturation is the amount of hue mixed into the color.
A color in the RGB space consists of red, green, and blue intensities.
Transform a colormap or image from red-green-blue (RGB) color space to luminance-chrominance (NTSC) space. The input may be of class uint8, uint16, single, or double. The output is of class double.
Implementation Note: The reference matrix for the transformation is
/Y\ 0.299 0.587 0.114 /R\ |I| = 0.596 -0.274 -0.322 |G| \Q/ 0.211 -0.523 0.312 \B/ |
as documented in http://en.wikipedia.org/wiki/YIQ and truncated to 3 significant figures. Note: The FCC version of NTSC uses only 2 significant digits and is slightly different.
Transform a colormap or image from luminance-chrominance (NTSC) space to red-green-blue (RGB) color space.
Implementation Note: The conversion matrix is chosen to be the inverse of the matrix used for rgb2ntsc such that
x == ntsc2rgb (rgb2ntsc (x)) |
MATLAB uses a slightly different matrix where rounding means the equality above does not hold.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave provides a few functions for dealing with audio data. An audio ‘sample’ is a single output value from an A/D converter, i.e., a small integer number (usually 8 or 16 bits), and audio data is just a series of such samples. It can be characterized by three parameters: the sampling rate (measured in samples per second or Hz, e.g., 8000 or 44100), the number of bits per sample (e.g., 8 or 16), and the number of channels (1 for mono, 2 for stereo, etc.).
There are many different formats for representing such data. Currently,
only the two most popular, linear encoding and mu-law
encoding, are supported by Octave. There is an excellent FAQ on audio
formats by Guido van Rossum guido@cwi.nl which can be found at any
FAQ ftp site, in particular in the directory
‘/pub/usenet/news.answers/audio-fmts’ of the archive site
rtfm.mit.edu.
Octave simply treats audio data as vectors of samples (non-mono data are not supported yet). It is assumed that audio files using linear encoding have one of the extensions ‘lin’ or ‘raw’, and that files holding data in mu-law encoding end in ‘au’, ‘mu’, or ‘snd’.
Convert audio data from linear to mu-law. Mu-law values use 8-bit unsigned integers. Linear values use n-bit signed integers or floating point values in the range -1 ≤ x ≤ 1 if n is 0.
If n is not specified it defaults to 0, 8, or 16 depending on the range of values in x.
Convert audio data from mu-law to linear. Mu-law values are 8-bit unsigned integers. Linear values use n-bit signed integers or floating point values in the range -1≤y≤1 if n is 0.
If n is not specified it defaults to 0.
Load audio data from the file ‘name.ext’ into the vector x.
The extension ext determines how the data in the audio file is interpreted; the extensions ‘lin’ (default) and ‘raw’ correspond to linear, the extensions ‘au’, ‘mu’, or ‘snd’ to mu-law encoding.
The argument bps can be either 8 (default) or 16, and specifies the number of bits per sample used in the audio file.
See also: lin2mu, mu2lin, saveaudio, playaudio, setaudio, record.
Save a vector x of audio data to the file
‘name.ext’. The optional parameters ext and
bps determine the encoding and the number of bits per sample used
in the audio file (see loadaudio); defaults are ‘lin’ and
8, respectively.
See also: lin2mu, mu2lin, loadaudio, playaudio, setaudio, record.
The following functions for audio I/O require special A/D hardware and operating system support. It is assumed that audio data in linear encoding can be played and recorded by reading from and writing to ‘/dev/dsp’, and that similarly ‘/dev/audio’ is used for mu-law encoding. These file names are system-dependent. Improvements so that these functions will work without modification on a wide variety of hardware are welcome.
Play the audio file ‘name.ext’ or the audio data stored in the vector x.
See also: lin2mu, mu2lin, loadaudio, saveaudio, setaudio, record.
Record sec seconds of audio input into the vector x. The default value for sampling_rate is 8000 samples per second, or 8kHz. The program waits until the user types <RET> and then immediately starts to record.
See also: lin2mu, mu2lin, loadaudio, saveaudio, playaudio, setaudio.
Execute the shell command ‘mixer’, possibly with optional arguments w_type and value.
Load the RIFF/WAVE sound file filename, and return the samples in vector y. If the file contains multichannel data, then y is a matrix with the channels represented as columns.
[y, Fs, bps] = wavread (filename)
Additionally return the sample rate (fs) in Hz and the number of bits per sample (bps).
[…] = wavread (filename, n)
Read only the first n samples from each channel.
wavread (filename, [n1 n2])
Read only samples n1 through n2 from each channel.
[samples, channels] = wavread (filename, "size")
Return the number of samples (n) and number of channels (ch) instead of the audio data.
See also: wavwrite.
Write y to the canonical RIFF/WAVE sound file filename with sample rate Fs and bits per sample bps. The default sample rate is 8000 Hz with 16-bits per sample. Each column of the data represents a separate channel. If y is either a row vector or a column vector, it is written as a single channel.
See also: wavread.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave includes the capability to include user classes, including the features of operator and function overloading. Equally a user class can be used to encapsulate certain properties of the class so that they cannot be altered accidentally and can be set up to address the issue of class precedence in mixed class operations.
This chapter discussions the means of constructing a user class with the example of a polynomial class, how to query and set the properties of this class, together with the means to overload operators and functions.
| 34.1 Creating a Class | ||
| 34.2 Manipulating Classes | ||
| 34.3 Indexing Objects | ||
| 34.4 Overloading Objects | ||
| 34.5 Inheritance and Aggregation |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
We use in the following text a polynomial class to demonstrate the use of object oriented programming within Octave. This class was chosen as it is simple, and so doesn’t distract unnecessarily from the discussion of the programming features of Octave. However, even still a small understand of the polynomial class itself is necessary to fully grasp the techniques described.
The polynomial class is used to represent polynomials of the form
a0 + a1 * x + a2 * x^2 + … + an * x^n |
where a0, a1, etc. are real scalars. Thus the polynomial can be represented by a vector
a = [a0, a1, a2, …, an]; |
We therefore now have sufficient information about the requirements of the class constructor for our polynomial class to write it. All object oriented classes in Octave, must be contained with a directory taking the name of the class, prepended with the @ symbol. For example, with our polynomial class, we would place the methods defining the class in the @polynomial directory.
The constructor of the class, must have the name of the class itself and so in our example the constructor with have the name ‘@polynomial/polynomial.m’. Also ideally when the constructor is called with no arguments to should return a value object. So for example our polynomial might look like
## -*- texinfo -*-
## @deftypefn {Function File} {} polynomial ()
## @deftypefnx {Function File} {} polynomial (@var{a})
## Create a polynomial object representing the polynomial
##
## @example
## a0 + a1 * x + a2 * x^2 + @dots{} + an * x^n
## @end example
##
## @noindent
## from a vector of coefficients [a0 a1 a2 @dots{} an].
## @end deftypefn
function p = polynomial (a)
if (nargin == 0)
p.poly = [0];
p = class (p, "polynomial");
elseif (nargin == 1)
if (strcmp (class (a), "polynomial"))
p = a;
elseif (isvector (a) && isreal (a))
p.poly = a(:).';
p = class (p, "polynomial");
else
error ("polynomial: expecting real vector");
endif
else
print_usage ();
endif
endfunction
|
Note that the return value of the constructor must be the output of
the class function called with the first argument being a
structure and the second argument being the class name. An example of
the call to this constructor function is then
p = polynomial ([1, 0, 1]); |
Note that methods of a class can be documented. The help for the
constructor itself can be obtained with the constructor name, that is
for the polynomial constructor help polynomial will return the
help string. Also the help can be obtained by restricting the search
for the help to a particular class, for example help
@polynomial/polynomial. This second method is the only means of
getting help for the overloaded methods and functions of the class.
The same is true for other Octave functions that take a function name
as an argument. For example type @polynomial/display will
print the code of the display method of the polynomial class to the
screen, and dbstop @polynomial/display will set a breakpoint
at the first executable line of the display method of the polynomial
class.
To check where a variable is a user class, the isobject and
isa functions can be used. For example:
p = polynomial ([1, 0, 1]); isobject (p) ⇒ 1 isa (p, "polynomial") ⇒ 1 |
Return true if x is a class object.
The available methods of a class can be displayed with the
methods function.
Return a cell array containing the names of the methods for the object obj or the named class classname. obj may be an Octave class object or a Java object.
See also: fieldnames.
To inquire whether a particular method is available to a user class, the
ismethod function can be used.
Return true if x is a class object and the string method is a method of this class.
For example:
p = polynomial ([1, 0, 1]); ismethod (p, "roots") ⇒ 1 |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There are a number of basic classes methods that can be defined to allow
the contents of the classes to be queried and set. The most basic of
these is the display method. The display method is used
by Octave when displaying a class on the screen, due to an expression
that is not terminated with a semicolon. If this method is not defined,
then Octave will printed nothing when displaying the contents of a class.
Display the contents of an object. If a is an object of the
class "myclass", then display is called in a case like
myclass (…) |
where Octave is required to display the contents of a variable of the
type "myclass".
An example of a display method for the polynomial class might be
function display (p)
a = p.poly;
first = true;
fprintf ("%s =", inputname (1));
for i = 1 : length (a);
if (a(i) != 0)
if (first)
first = false;
elseif (a(i) > 0)
fprintf (" +");
endif
if (a(i) < 0)
fprintf (" -");
endif
if (i == 1)
fprintf (" %g", abs (a(i)));
elseif (abs(a(i)) != 1)
fprintf (" %g *", abs (a(i)));
endif
if (i > 1)
fprintf (" X");
endif
if (i > 2)
fprintf (" ^ %d", i - 1);
endif
endif
endfor
if (first)
fprintf (" 0");
endif
fprintf ("\n");
endfunction
|
Note that in the display method, it makes sense to start the method
with the line fprintf ("%s =", inputname (1)) to be consistent
with the rest of Octave and print the variable name to be displayed
when displaying the class.
To be consistent with the Octave graphic handle classes, a class
should also define the get and set methods. The
get method should accept one or two arguments, and given one
argument of the appropriate class it should return a structure with
all of the properties of the class. For example:
function s = get (p, f)
if (nargin == 1)
s.poly = p.poly;
elseif (nargin == 2)
if (ischar (f))
switch (f)
case "poly"
s = p.poly;
otherwise
error ("get: invalid property %s", f);
endswitch
else
error ("get: expecting the property to be a string");
endif
else
print_usage ();
endif
endfunction
|
Similarly, the set method should taken as its first argument an
object to modify, and then take property/value pairs to be modified.
function s = set (p, varargin)
s = p;
if (length (varargin) < 2 || rem (length (varargin), 2) != 0)
error ("set: expecting property/value pairs");
endif
while (length (varargin) > 1)
prop = varargin{1};
val = varargin{2};
varargin(1:2) = [];
if (ischar (prop) && strcmp (prop, "poly"))
if (isvector (val) && isreal (val))
s.poly = val(:).';
else
error ("set: expecting the value to be a real vector");
endif
else
error ("set: invalid property of polynomial class");
endif
endwhile
endfunction
|
Note that as Octave does not implement pass by reference, than the
modified object is the return value of the set method and it
must be called like
p = set (p, "a", [1, 0, 0, 0, 1]); |
Also the set method makes use of the subsasgn method of
the class, and this method must be defined. The subsasgn method
is discussed in the next section.
Finally, user classes can be considered as a special type of a structure, and so they can be saved to a file in the same manner as a structure. For example:
p = polynomial ([1, 0, 1]); save userclass.mat p clear p load userclass.mat |
All of the file formats supported by save and load are
supported. In certain circumstances, a user class might either contain
a field that it makes no sense to save or a field that needs to be
initialized before it is saved. This can be done with the
saveobj method of the class
Method of a class to manipulate an object prior to saving it to a file.
The function saveobj is called when the object a is saved
using the save function. An example of the use of saveobj
might be to remove fields of the object that don’t make sense to be saved
or it might be used to ensure that certain fields of the object are
initialized before the object is saved. For example:
function b = saveobj (a)
b = a;
if (isempty (b.field))
b.field = initfield (b);
endif
endfunction
|
saveobj is called just prior to saving the class to a
file. Likely, the loadobj method is called just after a class
is loaded from a file, and can be used to ensure that any removed
fields are reinserted into the user object.
Method of a class to manipulate an object after loading it from a file.
The function loadobj is called when the object a is loaded
using the load function. An example of the use of saveobj
might be to add fields to an object that don’t make sense to be saved.
For example:
function b = loadobj (a) b = a; b.addmissingfield = addfield (b); endfunction |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 34.3.1 Defining Indexing And Indexed Assignment | ||
| 34.3.2 Indexed Assignment Optimization |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Objects can be indexed with parentheses, either like
a (idx) or like a {idx}, or even
like a (idx).field. However, it is up to the user
to decide what this indexing actually means. In the case of our polynomial
class p (n) might mean either the coefficient of the
n-th power of the polynomial, or it might be the evaluation of the
polynomial at n. The meaning of this subscripted referencing is
determined by the subsref method.
Perform the subscripted element selection operation according to the subscript specified by idx.
The subscript idx is expected to be a structure array with fields ‘type’ and ‘subs’. Valid values for ‘type’ are ‘"()"’, ‘"{}"’, and ‘"."’. The ‘subs’ field may be either ‘":"’ or a cell array of index values.
The following example shows how to extract the first two columns of a matrix
val = magic (3)
⇒ val = [ 8 1 6
3 5 7
4 9 2 ]
idx.type = "()";
idx.subs = {":", 1:2};
subsref (val, idx)
⇒ [ 8 1
3 5
4 9 ]
|
Note that this is the same as writing val(:,1:2).
If idx is an empty structure array with fields ‘type’ and ‘subs’, return val.
For example we might decide that indexing with "()" evaluates the
polynomial and indexing with "{}" returns the n-th coefficient
(of n-th power). In this case the subsref method of our
polynomial class might look like
function b = subsref (a, s)
if (isempty (s))
error ("polynomial: missing index");
endif
switch (s(1).type)
case "()"
ind = s(1).subs;
if (numel (ind) != 1)
error ("polynomial: need exactly one index");
else
b = polyval (fliplr (a.poly), ind{1});
endif
case "{}"
ind = s(1).subs;
if (numel (ind) != 1)
error ("polynomial: need exactly one index");
else
if (isnumeric (ind{1}))
b = a.poly(ind{1}+1);
else
b = a.poly(ind{1});
endif
endif
case "."
fld = s.subs;
if (strcmp (fld, "poly"))
b = a.poly;
else
error ("@polynomial/subsref: invalid property \"%s\"", fld);
endif
otherwise
error ("invalid subscript type");
endswitch
if (numel (s) > 1)
b = subsref (b, s(2:end));
endif
endfunction
|
The equivalent functionality for subscripted assignments uses the
subsasgn method.
Perform the subscripted assignment operation according to the subscript specified by idx.
The subscript idx is expected to be a structure array with fields ‘type’ and ‘subs’. Valid values for ‘type’ are ‘"()"’, ‘"{}"’, and ‘"."’. The ‘subs’ field may be either ‘":"’ or a cell array of index values.
The following example shows how to set the two first columns of a 3-by-3 matrix to zero.
val = magic (3);
idx.type = "()";
idx.subs = {":", 1:2};
subsasgn (val, idx, 0)
⇒ [ 0 0 6
0 0 7
0 0 2 ]
|
Note that this is the same as writing val(:,1:2) = 0.
If idx is an empty structure array with fields ‘type’ and ‘subs’, return rhs.
Query or set the internal flag for subsasgn method call optimizations.
If true, Octave will attempt to eliminate the redundant copying when calling the subsasgn method of a user-defined class.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
Note that the subsref and subsasgn methods always receive the
whole index chain, while they usually handle only the first element. It is the
responsibility of these methods to handle the rest of the chain (if needed),
usually by forwarding it again to subsref or subsasgn.
If you wish to use the end keyword in subscripted expressions
of an object, then the user needs to define the end method for
the class. For example, the end method for our polynomial class might
look like
function r = end (obj, index_pos, num_indices)
if (num_indices != 1)
error ("polynomial object may only have one index")
endif
r = length (obj.poly) - 1;
endfunction
|
which is a fairly generic end method that has a behavior similar to
the end keyword for Octave Array classes. It can then be used as
follows:
p = polynomial ([1,2,3,4]); p(end-1) ⇒ 3 |
Objects can also be used as the index in a subscripted expression themselves
and this is controlled with the subsindex function.
Convert an object to an index vector. When a is a class object
defined with a class constructor, then subsindex is the
overloading method that allows the conversion of this class object to
a valid indexing vector. It is important to note that
subsindex must return a zero-based real integer vector of the
class "double". For example, if the class constructor
function b = myclass (a)
b = class (struct ("a", a), "myclass");
endfunction
|
then the subsindex function
function idx = subsindex (a) idx = double (a.a) - 1.0; endfunction |
can then be used as follows
a = myclass (1:4); b = 1:10; b(a) ⇒ 1 2 3 4 |
Finally, objects can equally be used like ranges, using the colon
method
Method of a class to construct a range with the : operator. For
example:
a = myclass (…); b = myclass (…); c = a : b |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave’s ubiquitous lazily-copied pass-by-value semantics implies a problem for performance of user-defined subsasgn methods. Imagine a call to subsasgn:
ss = substruct ("()",{1});
x = subsasgn (x, ss, 1);
|
and the corresponding method looking like this:
function x = subsasgn (x, ss, val)
…
x.myfield (ss.subs{1}) = val;
endfunction
|
The problem is that on entry to the subsasgn method, x is still
referenced from the caller’s scope, which means that the method will
first need to unshare (copy) x and x.myfield before performing
the assignment. Upon completing the call, unless an error occurs,
the result is immediately assigned to x in the caller’s scope,
so that the previous value of x.myfield is forgotten. Hence, the
Octave language implies a copy of N elements (N being the size of
x.myfield), where modifying just a single element would actually
suffice, i.e., degrades a constant-time operation to linear-time one.
This may be a real problem for user classes that intrinsically store large
arrays.
To partially solve the problem, Octave uses a special optimization for user-defined subsasgn methods coded as m-files. When the method gets called as a result of the built-in assignment syntax (not direct subsasgn call as shown above), i.e.
x(1) = 1; |
AND if the subsasgn method is declared with identical input and output argument,
like in the example above, then Octave will ignore the copy of x inside
the caller’s scope; therefore, any changes made to x during the method
execution will directly affect the caller’s copy as well.
This allows, for instance, defining a polynomial class where modifying a single
element takes constant time.
It is important to understand the implications that this optimization brings.
Since no extra copy of x in the caller’s scope will exist, it is
solely the callee’s responsibility to not leave x in an invalid
state if an error occurs throughout the execution. Also, if the method
partially changes x and then errors out, the changes will affect
x in the caller’s scope. Deleting or completely replacing x
inside subsasgn will not do anything, however, only indexed assignments matter.
Since this optimization may change the way code works (especially if badly
written), a built-in variable optimize_subsasgn_calls is provided to
control it. It is on by default. Another option to avoid the effect is to
declare subsasgn methods with different output and input arguments, like this:
function y = subsasgn (x, ss, val)
…
endfunction
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 34.4.1 Function Overloading | ||
| 34.4.2 Operator Overloading | ||
| 34.4.3 Precedence of Objects |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Any Octave function can be overloaded, and allows an object specific
version of this function to be called as needed. A pertinent example
for our polynomial class might be to overload the polyval function
like
function [y, dy] = polyval (p, varargin)
if (nargout == 2)
[y, dy] = polyval (fliplr (p.poly), varargin{:});
else
y = polyval (fliplr (p.poly), varargin{:});
endif
endfunction
|
This function just hands off the work to the normal Octave polyval
function. Another interesting example for an overloaded function for our
polynomial class is the plot function.
function h = plot (p, varargin)
n = 128;
rmax = max (abs (roots (p.poly)));
x = [0 : (n - 1)] / (n - 1) * 2.2 * rmax - 1.1 * rmax;
if (nargout > 0)
h = plot (x, p(x), varargin{:});
else
plot (x, p(x), varargin{:});
endif
endfunction
|
which allows polynomials to be plotted in the domain near the region of the roots of the polynomial.
Functions that are of particular interest to be overloaded are the class
conversion functions such as double. Overloading these functions
allows the cast function to work with the user class and can aid
in the use of methods of other classes with the user class. An example
double function for our polynomial class might look like.
function b = double (a) b = a.poly; endfunction |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following table shows, for each built-in numerical operation, the corresponding function name to use when providing an overloaded method for a user class.
| Operation | Method | Description | ||
|---|---|---|---|---|
| a + b | plus (a, b) | Binary addition | ||
| a - b | minus (a, b) | Binary subtraction operator | ||
| + a | uplus (a) | Unary addition operator | ||
| - a | uminus (a) | Unary subtraction operator | ||
| a .* b | times (a, b) | Element-wise multiplication operator | ||
| a * b | mtimes (a, b) | Matrix multiplication operator | ||
| a ./ b | rdivide (a, b) | Element-wise right division operator | ||
| a / b | mrdivide (a, b) | Matrix right division operator | ||
| a .\ b | ldivide (a, b) | Element-wise left division operator | ||
| a \ b | mldivide (a, b) | Matrix left division operator | ||
| a .^ b | power (a, b) | Element-wise power operator | ||
| a ^ b | mpower (a, b) | Matrix power operator | ||
| a < b | lt (a, b) | Less than operator | ||
| a <= b | le (a, b) | Less than or equal to operator | ||
| a > b | gt (a, b) | Greater than operator | ||
| a >= b | ge (a, b) | Greater than or equal to operator | ||
| a == b | eq (a, b) | Equal to operator | ||
| a != b | ne (a, b) | Not equal to operator | ||
| a & b | and (a, b) | Logical and operator | ||
| a | b | or (a, b) | Logical or operator | ||
| ! b | not (a) | Logical not operator | ||
| a’ | ctranspose (a) | Complex conjugate transpose operator | ||
| a.’ | transpose (a) | Transpose operator | ||
| a : b | colon (a, b) | Two element range operator | ||
| a : b : c | colon (a, b, c) | Three element range operator | ||
| [a, b] | horzcat (a, b) | Horizontal concatenation operator | ||
| [a; b] | vertcat (a, b) | Vertical concatenation operator | ||
| a(s_1, …, s_n) | subsref (a, s) | Subscripted reference | ||
| a(s_1, …, s_n) = b | subsasgn (a, s, b) | Subscripted assignment | ||
| b (a) | subsindex (a) | Convert to zero-based index | ||
| display | display (a) | Commandline display function |
Table 34.1: Available overloaded operators and their corresponding class method
An example mtimes method for our polynomial class might look like
function y = mtimes (a, b) y = polynomial (conv (double (a), double (b))); endfunction |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Many functions and operators take two or more arguments and so the
case can easily arise that these functions are called with objects of
different classes. It is therefore necessary to determine the precedence
of which method of which class to call when there are mixed objects given
to a function or operator. To do this the superiorto and
inferiorto functions can be used
When called from a class constructor, mark the object currently constructed as having a higher precedence than class_name. More that one such class can be specified in a single call. This function may only be called from a class constructor.
See also: inferiorto.
When called from a class constructor, mark the object currently constructed as having a lower precedence than class_name. More that one such class can be specified in a single call. This function may only be called from a class constructor.
See also: superiorto.
For example with our polynomial class consider the case
2 * polynomial ([1, 0, 1]); |
That mixes an object of the class "double" with an object of the class
"polynomial". In this case we like to ensure that the return type of
the above is of the type "polynomial" and so we use the
superiorto function in the class constructor. In particular our
polynomial class constructor would be modified to be
## -*- texinfo -*-
## @deftypefn {Function File} {} polynomial ()
## @deftypefnx {Function File} {} polynomial (@var{a})
## Create a polynomial object representing the polynomial
##
## @example
## a0 + a1 * x + a2 * x^2 + @dots{} + an * x^n
## @end example
##
## @noindent
## from a vector of coefficients [a0 a1 a2 @dots{} an].
## @end deftypefn
function p = polynomial (a)
if (nargin == 0)
p.poly = [0];
p = class (p, "polynomial");
elseif (nargin == 1)
if (strcmp (class (a), "polynomial"))
p = a;
elseif (isvector (a) && isreal (a))
p.poly = a(:).';
p = class (p, "polynomial");
else
error ("polynomial: expecting real vector");
endif
else
print_usage ();
endif
superiorto ("double");
endfunction
|
Note that user classes always have higher precedence than built-in
Octave types. So in fact marking our polynomial class higher than the
"double" class is in fact not necessary.
When faced with two objects that have the same precedence, Octave will use the method of the object that appears first on the list of arguments.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Using classes to build new classes is supported by octave through the use of both inheritance and aggregation.
Class inheritance is provided by octave using the class
function in the class constructor. As in the case of the polynomial
class, the octave programmer will create a struct that contains the
data fields required by the class, and then call the class function to
indicate that an object is to be created from the struct. Creating a
child of an existing object is done by creating an object of the
parent class and providing that object as the third argument of the
class function.
This is easily demonstrated by example. Suppose the programmer needs an FIR filter, i.e., a filter with a numerator polynomial but a unity denominator polynomial. In traditional octave programming, this would be performed as follows.
octave:1> x = [some data vector]; octave:2> n = [some coefficient vector]; octave:3> y = filter (n, 1, x); |
The equivalent class could be implemented in a class directory @FIRfilter that is on the octave path. The constructor is a file FIRfilter.m in the class directory.
## -*- texinfo -*-
## @deftypefn {Function File} {} FIRfilter ()
## @deftypefnx {Function File} {} FIRfilter (@var{p})
## Create a FIR filter with polynomial @var{p} as coefficient vector.
## @end deftypefn
function f = FIRfilter (p)
f.polynomial = [];
if (nargin == 0)
p = @polynomial ([1]);
elseif (nargin == 1)
if (!isa (p, "polynomial"))
error ("FIRfilter: expecting polynomial as input argument");
endif
else
print_usage ();
endif
f = class (f, "FIRfilter", p);
endfunction
|
As before, the leading comments provide command-line documentation for
the class constructor. This constructor is very similar to the
polynomial class constructor, except that we pass a polynomial object
as the third argument to the class function, telling octave that the
FIRfilter class will be derived from the polynomial class. Our FIR
filter does not have any data fields, but we must provide a struct to
the class function. The class function will add an
element named polynomial to the object struct, so we simply add a
dummy element named polynomial as the first line of the constructor.
This dummy element will be overwritten by the class function.
Note further that all our examples provide for the case in which no arguments are supplied. This is important since octave will call the constructor with no arguments when loading objects from save files to determine the inheritance structure.
A class may be a child of more than one class (see the documentation
for the class function), and inheritance may be nested. There
is no limitation to the number of parents or the level of nesting
other than memory or other physical issues.
As before, we need a display method. A simple example might be
function display (f) display (f.polynomial); endfunction |
Note that we have used the polynomial field of the struct to display the filter coefficients.
Once we have the class constructor and display method, we may create an object by calling the class constructor. We may also check the class type and examine the underlying structure.
octave:1> f = FIRfilter (polynomial ([1 1 1]/3))
f.polynomial = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2
octave:2> class (f)
ans = FIRfilter
octave:3> isa (f,"FIRfilter")
ans = 1
octave:4> isa (f,"polynomial")
ans = 1
octave:5> struct (f)
ans =
{
polynomial = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2
}
|
We only need to define a method to actually process data with our
filter and our class is usable. It is also useful to provide a means
of changing the data stored in the class. Since the fields in the
underlying struct are private by default, we could provide a mechanism
to access the fields. The subsref method may be used for both.
function out = subsref (f, x)
switch (x.type)
case "()"
n = f.polynomial;
out = filter (n.poly, 1, x.subs{1});
case "."
fld = x.subs;
if (strcmp (fld, "polynomial"))
out = f.polynomial;
else
error ("@FIRfilter/subsref: invalid property \"%s\"", fld);
endif
otherwise
error ("@FIRfilter/subsref: invalid subscript type for FIR filter");
endswitch
endfunction
|
The "()" case allows us to filter data using the polynomial provided
to the constructor.
octave:2> f = FIRfilter (polynomial ([1 1 1]/3)); octave:3> x = ones (5,1); octave:4> y = f(x) y = 0.33333 0.66667 1.00000 1.00000 1.00000 |
The "." case allows us to view the contents of the polynomial field.
octave:1> f = FIRfilter (polynomial ([1 1 1]/3)); octave:2> f.polynomial ans = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2 |
In order to change the contents of the object, we need to define a
subsasgn method. For example, we may make the polynomial field
publicly writable.
function out = subsasgn (f, index, val)
switch (index.type)
case "."
fld = index.subs;
if (strcmp (fld, "polynomial"))
out = f;
out.polynomial = val;
else
error ("@FIRfilter/subsref: invalid property \"%s\"", fld);
endif
otherwise
error ("FIRfilter/subsagn: Invalid index type")
endswitch
endfunction
|
So that
octave:6> f = FIRfilter (); octave:7> f.polynomial = polynomial ([1 2 3]); f.polynomial = 1 + 2 * X + 3 * X ^ 2 |
Defining the FIRfilter class as a child of the polynomial class implies that and FIRfilter object may be used any place that a polynomial may be used. This is not a normal use of a filter, so that aggregation may be a more sensible design approach. In this case, the polynomial is simply a field in the class structure. A class constructor for this case might be
## -*- texinfo -*-
## @deftypefn {Function File} {} FIRfilter ()
## @deftypefnx {Function File} {} FIRfilter (@var{p})
## Create a FIR filter with polynomial @var{p} as coefficient vector.
## @end deftypefn
function f = FIRfilter (p)
if (nargin == 0)
f.polynomial = @polynomial ([1]);
elseif (nargin == 1)
if (isa (p, "polynomial"))
f.polynomial = p;
else
error ("FIRfilter: expecting polynomial as input argument");
endif
else
print_usage ();
endif
f = class (f, "FIRfilter");
endfunction
|
For our example, the remaining class methods remain unchanged.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave is principally a batch or command-line language. However, it does offer some limited features for constructing graphical interfaces for interacting with users.
The GUI elements available are I/O dialogs and a progress bar. For example, rather than hardcoding a filename for output results a script can open a dialog box and allow the user to choose a file. Similarly, if a calculation is expected to take a long time a script can display a progress bar.
Several utility functions make it possible to store private data for use with a GUI which will not pollute the user’s variable space.
Finally, a program written in Octave might want to have long term storage of preferences or state variables. This can be done with user-defined preferences.
| 35.1 I/O Dialogs | ||
| 35.2 Progress Bar | ||
| 35.3 GUI Utility Functions | ||
| 35.4 User-Defined Preferences |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Simple dialog menus are available for choosing directories or files. They return a string variable which can then be used with any command requiring a file name.
Open a GUI dialog for selecting a directory. If init_path is not given the current working directory is used. dialog_name may be used to customize the dialog title.
Open a GUI dialog for selecting a file and return the filename fname, the path to this file fpath, and the filter index fltidx. flt contains a (list of) file filter string(s) in one of the following formats:
"/path/to/filename.ext"If a filename is given then the file extension is extracted and used as
filter. In addition, the path is selected as current path and the filename
is selected as default file. Example: uigetfile ("myfun.m")
"*.ext"Example: uigetfile ("*.ext")
containing a file extension in the first column and a brief description
in the second column.
Example: uigetfile ({"*.ext", "My Description";"*.xyz",
"XYZ-Format"})
The filter string can also contain a semicolon separated list of filter
extensions.
Example: uigetfile ({"*.gif;*.png;*.jpg", "Supported Picture
Formats"})
dialog_name can be used to customize the dialog title. If default_file is given then it will be selected in the GUI dialog. If, in addition, a path is given it is also used as current path.
The screen position of the GUI dialog can be set using the
"Position" key and a 2-element vector containing the pixel
coordinates. Two or more files can be selected when setting the
"MultiSelect" key to "on". In that case fname is a
cell array containing the files.
Open a GUI dialog for selecting a file. flt contains a (list of) file filter string(s) in one of the following formats:
"/path/to/filename.ext"If a filename is given the file extension is extracted and used as filter.
In addition the path is selected as current path and the filename is
selected as default file. Example: uiputfile ("myfun.m")
"*.ext"A single file extension.
Example: uiputfile ("*.ext")
{"*.ext", "My Description"}A 2-column cell array containing the file extension in the 1st column and
a brief description in the 2nd column.
Example: uiputfile ({"*.ext","My Description";"*.xyz",
"XYZ-Format"})
The filter string can also contain a semicolon separated list of filter
extensions.
Example: uiputfile ({"*.gif;*.png;*.jpg",
"Supported Picture Formats"})
dialog_name can be used to customize the dialog title. If default_file is given it is preselected in the GUI dialog. If, in addition, a path is given it is also used as current path.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Return a handle h to a new waitbar object.
The waitbar is filled to fraction frac which must be in the range [0, 1]. The optional message msg is centered and displayed above the waitbar. The appearance of the waitbar figure window can be configured by passing property/value pairs to the function.
When called with a single input the current waitbar, if it exists, is updated to the new value frac. If there are multiple outstanding waitbars they can be updated individually by passing the handle hwbar of the specific waitbar to modify.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
These functions do not implement a GUI element but are useful when developing
programs that do. Warning: The functions uiwait,
uiresume, and waitfor are only available for the FLTK tooolkit.
Return true if the desktop (GUI) is currently in use.
See also: isguirunning.
Query or set user-custom GUI data.
The GUI data is stored in the figure handle h. If h is not a figure handle then it’s parent figure will be used for storage.
data must be a single object which means it is usually preferable for it to be a data container such as a cell array or struct so that additional data items can be added easily.
See also: getappdata, setappdata, get, set, getpref, setpref.
Return a structure of object handles for the figure associated with handle h.
If no handle is specified the current figure returned by gcf is used.
The fieldname for each entry of hdata is taken from the "tag"
property of the graphic object. If the tag is empty then the handle is not
returned. If there are multiple graphic objects with the same tag then
the entry in hdata will be a vector of handles. guihandles
includes all possible handles, including those for
which "HandleVisibility" is "off".
Return true if Octave is running in GUI mode and false otherwise.
Suspend program execution until the figure with handle h is
deleted or uiresume is called. When no figure handle is specified,
this function uses the current figure.
If the figure handle is invalid or there is no current figure, this functions returns immediately.
When specified, timeout defines the number of seconds to wait
for the figure deletion or the uiresume call. The timeout value
must be at least 1. If a smaller value is specified, a warning is issued
and a timeout value of 1 is used instead. If a non-integer value is
specified, it is truncated towards 0. If timeout is not specified,
the program execution is suspended indefinitely.
Resume program execution suspended with uiwait. The handle h
must be the same as the on specified in uiwait. If the handle
is invalid or there is no uiwait call pending for the figure
with handle h, this function does nothing.
See also: uiwait.
Suspend the execution of the current program until a condition is satisfied on the graphics handle h.
While the program is suspended graphics events are still being processed
normally, allowing callbacks to modify the state of graphics objects. This
function is reentrant and can be called from a callback, while another
waitfor call is pending at the top-level.
In the first form, program execution is suspended until the graphics object h is destroyed. If the graphics handle is invalid, the function returns immediately.
In the second form, execution is suspended until the graphics object is destroyed or the property named prop is modified. If the graphics handle is invalid or the property does not exist, the function returns immediately.
In the third form, execution is suspended until the graphics object is
destroyed or the property named prop is set to value. The
function isequal is used to compare property values. If the graphics
handle is invalid, the property does not exist or the property is already
set to value, the function returns immediately.
An optional timeout can be specified using the property timeout.
This timeout value is the number of seconds to wait for the condition to be
true. timeout must be at least 1. If a smaller value is specified, a
warning is issued and a value of 1 is used instead. If the timeout value is
not an integer, it is truncated towards 0.
To define a condition on a property named timeout, use the string
\timeout instead.
In all cases, typing CTRL-C stops program execution immediately.
See also: waitforbuttonpress, isequal.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Return the preference value corresponding to the named preference pref in the preference group group.
The named preference group must be a character string.
If pref does not exist in group and default is specified, return default.
The preference pref may be a character string or a cell array of character strings. The corresponding default value default may be any value, or, if pref is a cell array of strings, default must be a cell array of values with the same size as pref.
If neither pref nor default are specified, return a structure of preferences for the preference group group.
If no arguments are specified, return a structure containing all groups of preferences and their values.
Set a preference pref to the given val in the named preference group group.
The named preference group must be a character string.
The preference pref may be a character string or a cell array of character strings. The corresponding value val may be any value, or, if pref is a cell array of strings, val must be a cell array of values with the same size as pref.
If the named preference or group does not exist, it is added.
Add a preference pref and associated value val to the named preference group group.
The named preference group must be a character string.
The preference pref may be a character string or a cell array of character strings. The corresponding value val may be any value, or, if pref is a cell array of strings, val must be a cell array of values with the same size as pref.
Remove the named preference pref from the preference group group.
The named preference group must be a character string.
The preference pref may be a character string or cell array of strings.
If pref is not specified, remove the preference group group.
It is an error to remove a nonexistent preference or group.
Return true if the named preference pref exists in the preference group group.
The named preference group must be a character string.
The preference pref may be a character string or a cell array of character strings.
If pref is not specified, return true if the preference group group exists.
Return the directory that contains the preferences for Octave.
Examples:
Display the preferences directory
prefdir |
Change to the preferences folder
cd (prefdir) |
Display the GUI preferences dialog window for Octave.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This chapter describes the functions that are available to allow you to get information about what is happening outside of Octave, while it is still running, and use this information in your program. For example, you can get information about environment variables, the current time, and even start other programs from the Octave prompt.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave’s core set of functions for manipulating time values are patterned after the corresponding functions from the standard C library. Several of these functions use a data structure for time that includes the following elements:
usecMicroseconds after the second (0-999999).
secSeconds after the minute (0-60). This number can be 60 to account for leap seconds.
minMinutes after the hour (0-59).
hourHours since midnight (0-23).
mdayDay of the month (1-31).
monMonths since January (0-11).
yearYears since 1900.
wdayDays since Sunday (0-6).
ydayDays since January 1 (0-365).
isdstDaylight Savings Time flag.
zoneTime zone.
In the descriptions of the following functions, this structure is referred to as a tm_struct.
Return the current time as the number of seconds since the epoch. The
epoch is referenced to 00:00:00 CUT (Coordinated Universal Time) 1 Jan
1970. For example, on Monday February 17, 1997 at 07:15:06 CUT, the
value returned by time was 856163706.
See also: strftime, strptime, localtime, gmtime, mktime, now, date, clock, datenum, datestr, datevec, calendar, weekday.
Return the current local date/time as a serial day number
(see datenum).
The integral part, floor (now) corresponds to the number of days
between today and Jan 1, 0000.
The fractional part, rem (now, 1) corresponds to the current
time.
Convert a value returned from time (or any other non-negative
integer), to the local time and return a string of the same form as
asctime. The function ctime (time) is equivalent to
asctime (localtime (time)). For example:
ctime (time ()) ⇒ "Mon Feb 17 01:15:06 1997" |
Given a value returned from time, or any non-negative integer,
return a time structure corresponding to CUT (Coordinated Universal Time).
For example:
gmtime (time ())
⇒ {
usec = 0
sec = 6
min = 15
hour = 7
mday = 17
mon = 1
year = 97
wday = 1
yday = 47
isdst = 0
zone = CST
}
|
See also: strftime, strptime, localtime, mktime, time, now, date, clock, datenum, datestr, datevec, calendar, weekday.
Given a value returned from time, or any non-negative integer,
return a time structure corresponding to the local time zone.
localtime (time ())
⇒ {
usec = 0
sec = 6
min = 15
hour = 1
mday = 17
mon = 1
year = 97
wday = 1
yday = 47
isdst = 0
zone = CST
}
|
See also: strftime, strptime, gmtime, mktime, time, now, date, clock, datenum, datestr, datevec, calendar, weekday.
Convert a time structure corresponding to the local time to the number of seconds since the epoch. For example:
mktime (localtime (time ()))
⇒ 856163706
|
See also: strftime, strptime, localtime, gmtime, time, now, date, clock, datenum, datestr, datevec, calendar, weekday.
Convert a time structure to a string using the following
format: "ddd mmm mm HH:MM:SS yyyy". For example:
asctime (localtime (time ()))
⇒ "Mon Feb 17 01:15:06 1997"
|
This is equivalent to ctime (time ()).
Format the time structure tm_struct in a flexible way using the
format string fmt that contains ‘%’ substitutions
similar to those in printf. Except where noted, substituted
fields have a fixed size; numeric fields are padded if necessary.
Padding is with zeros by default; for fields that display a single
number, padding can be changed or inhibited by following the ‘%’
with one of the modifiers described below. Unknown field specifiers are
copied as normal characters. All other characters are copied to the
output without change. For example:
strftime ("%r (%Z) %A %e %B %Y", localtime (time ()))
⇒ "01:15:06 AM (CST) Monday 17 February 1997"
|
Octave’s strftime function supports a superset of the ANSI C
field specifiers.
Literal character fields:
%%% character.
%nNewline character.
%tTab character.
Numeric modifiers (a nonstandard extension):
- (dash)Do not pad the field.
_ (underscore)Pad the field with spaces.
Time fields:
%HHour (00-23).
%IHour (01-12).
%kHour (0-23).
%lHour (1-12).
%MMinute (00-59).
%pLocale’s AM or PM.
%rTime, 12-hour (hh:mm:ss [AP]M).
%RTime, 24-hour (hh:mm).
%sTime in seconds since 00:00:00, Jan 1, 1970 (a nonstandard extension).
%SSecond (00-61).
%TTime, 24-hour (hh:mm:ss).
%XLocale’s time representation (%H:%M:%S).
%ZTime zone (EDT), or nothing if no time zone is determinable.
Date fields:
%aLocale’s abbreviated weekday name (Sun-Sat).
%ALocale’s full weekday name, variable length (Sunday-Saturday).
%bLocale’s abbreviated month name (Jan-Dec).
%BLocale’s full month name, variable length (January-December).
%cLocale’s date and time (Sat Nov 04 12:02:33 EST 1989).
%CCentury (00-99).
%dDay of month (01-31).
%eDay of month ( 1-31).
%DDate (mm/dd/yy).
%hSame as %b.
%jDay of year (001-366).
%mMonth (01-12).
%UWeek number of year with Sunday as first day of week (00-53).
%wDay of week (0-6).
%WWeek number of year with Monday as first day of week (00-53).
%xLocale’s date representation (mm/dd/yy).
%yLast two digits of year (00-99).
%YYear (1970-).
See also: strptime, localtime, gmtime, mktime, time, now, date, clock, datenum, datestr, datevec, calendar, weekday.
Convert the string str to the time structure tm_struct under the control of the format string fmt.
If fmt fails to match, nchars is 0; otherwise, it is set to the position of last matched character plus 1. Always check for this unless you’re absolutely sure the date string will be parsed correctly.
See also: strftime, localtime, gmtime, mktime, time, now, date, clock, datenum, datestr, datevec, calendar, weekday.
Most of the remaining functions described in this section are not patterned after the standard C library. Some are available for compatibility with MATLAB and others are provided because they are useful.
Return the current local date and time as a date vector. The date vector contains the following fields: current year, month (1-12), day (1-31), hour (0-23), minute (0-59), and second (0-61). The seconds field has a fractional part after the decimal point for extended accuracy.
For example:
fix (clock ())
⇒ [ 1993, 8, 20, 4, 56, 1 ]
|
The function clock is more accurate on systems that have the
gettimeofday function.
Return the current date as a character string in the form DD-MMM-YYYY.
For example:
date () ⇒ "20-Aug-1993" |
Return the difference in seconds between two time values returned from
clock (t2 - t1). For example:
t0 = clock (); # many computations later… elapsed_time = etime (clock (), t0); |
will set the variable elapsed_time to the number of seconds since
the variable t0 was set.
Return the CPU time used by your Octave session. The first output is
the total time spent executing your process and is equal to the sum of
second and third outputs, which are the number of CPU seconds spent
executing in user mode and the number of CPU seconds spent executing in
system mode, respectively. If your system does not have a way to report
CPU time usage, cputime returns 0 for each of its output values.
Note that because Octave used some CPU time to start, it is reasonable
to check to see if cputime works by checking to see if the total
CPU time used is nonzero.
Return true if year is a leap year and false otherwise. If no
year is specified, is_leap_year uses the current year.
For example:
is_leap_year (2000) ⇒ 1 |
Set or check a wall-clock timer. Calling tic without an
output argument sets the internal timer state. Subsequent calls
to toc return the number of seconds since the timer was set.
For example,
tic (); # many computations later… elapsed_time = toc (); |
will set the variable elapsed_time to the number of seconds since
the most recent call to the function tic.
If called with one output argument, tic returns a scalar
of type uint64 that may be later passed to toc.
id = tic; sleep (5); toc (id)
⇒ 5.0010
|
Calling tic and toc this way allows nested timing calls.
If you are more interested in the CPU time that your process used, you
should use the cputime function instead. The tic and
toc functions report the actual wall clock time that elapsed
between the calls. This may include time spent processing other jobs or
doing nothing at all.
Suspend the execution of the program for n seconds.
n is a positive real value and may be a fraction of a second. If invoked without an input arguments then the program is suspended until a character is typed.
The following example prints a message and then waits 5 seconds before clearing the screen.
fprintf (stderr, "wait please...\n"); pause (5); clc; |
Suspend the execution of the program for the given number of seconds.
Suspend the execution of the program for the given number of
microseconds. On systems where it is not possible to sleep for periods
of time less than one second, usleep will pause the execution for
round (microseconds / 1e6) seconds.
Return the date/time input as a serial day number, with Jan 1, 0000 defined as day 1.
The integer part, floor (days) counts the number of
complete days in the date input.
The fractional part, rem (days, 1) corresponds to the time
on the given day.
The input may be a date vector (see datevec),
datestr (see datestr), or directly specified as input.
When processing input datestrings, p is the year at the start of the century to which two-digit years will be referenced. If not specified, it defaults to the current year minus 50.
The optional output secs holds the time on the specified day with greater precision than days.
Notes:
Caution: this function does not attempt to handle Julian calendars so dates before October 15, 1582 are wrong by as much as eleven days. Also, be aware that only Roman Catholic countries adopted the calendar in 1582. It took until 1924 for it to be adopted everywhere. See the Wikipedia entry on the Gregorian calendar for more details.
Warning: leap seconds are ignored. A table of leap seconds is available on the Wikipedia entry for leap seconds.
Format the given date/time according to the format f and return
the result in str. date is a serial date number (see
datenum) or a date vector (see datevec). The value of
date may also be a string or cell array of strings.
f can be an integer which corresponds to one of the codes in the table below, or a date format string.
p is the year at the start of the century in which two-digit years are to be interpreted in. If not specified, it defaults to the current year minus 50.
For example, the date 730736.65149 (2000-09-07 15:38:09.0934) would be formatted as follows:
| Code | Format | Example |
|---|---|---|
| 0 | dd-mmm-yyyy HH:MM:SS | 07-Sep-2000 15:38:09 |
| 1 | dd-mmm-yyyy | 07-Sep-2000 |
| 2 | mm/dd/yy | 09/07/00 |
| 3 | mmm | Sep |
| 4 | m | S |
| 5 | mm | 09 |
| 6 | mm/dd | 09/07 |
| 7 | dd | 07 |
| 8 | ddd | Thu |
| 9 | d | T |
| 10 | yyyy | 2000 |
| 11 | yy | 00 |
| 12 | mmmyy | Sep00 |
| 13 | HH:MM:SS | 15:38:09 |
| 14 | HH:MM:SS PM | 03:38:09 PM |
| 15 | HH:MM | 15:38 |
| 16 | HH:MM PM | 03:38 PM |
| 17 | QQ-YY | Q3-00 |
| 18 | Q3 | |
| 19 | dd/mm | 07/09 |
| 20 | dd/mm/yy | 07/09/00 |
| 21 | mmm.dd,yyyy HH:MM:SS | Sep.07,2000 15:38:08 |
| 22 | mmm.dd,yyyy | Sep.07,2000 |
| 23 | mm/dd/yyyy | 09/07/2000 |
| 24 | dd/mm/yyyy | 07/09/2000 |
| 25 | yy/mm/dd | 00/09/07 |
| 26 | yyyy/mm/dd | 2000/09/07 |
| 27 | QQ-YYYY | Q3-2000 |
| 28 | mmmyyyy | Sep2000 |
| 29 | yyyy-mm-dd | 2000-09-07 |
| 30 | yyyymmddTHHMMSS | 20000907T153808 |
| 31 | yyyy-mm-dd HH:MM:SS | 2000-09-07 15:38:08 |
If f is a format string, the following symbols are recognized:
| Symbol | Meaning | Example |
|---|---|---|
| yyyy | Full year | 2005 |
| yy | Two-digit year | 05 |
| mmmm | Full month name | December |
| mmm | Abbreviated month name | Dec |
| mm | Numeric month number (padded with zeros) | 01, 08, 12 |
| m | First letter of month name (capitalized) | D |
| dddd | Full weekday name | Sunday |
| ddd | Abbreviated weekday name | Sun |
| dd | Numeric day of month (padded with zeros) | 11 |
| d | First letter of weekday name (capitalized) | S |
| HH | Hour of day, padded with zeros if PM is set | 09:00 |
| and not padded with zeros otherwise | 9:00 AM | |
| MM | Minute of hour (padded with zeros) | 10:05 |
| SS | Second of minute (padded with zeros) | 10:05:03 |
| FFF | Milliseconds of second (padded with zeros) | 10:05:03.012 |
| AM | Use 12-hour time format | 11:30 AM |
| PM | Use 12-hour time format | 11:30 PM |
If f is not specified or is -1, then use 0, 1 or 16,
depending on whether the date portion or the time portion of
date is empty.
If p is nor specified, it defaults to the current year minus 50.
If a matrix or cell array of dates is given, a column vector of date strings is returned.
Convert a serial date number (see datenum) or date string (see
datestr) into a date vector.
A date vector is a row vector with six members, representing the year, month, day, hour, minute, and seconds respectively.
f is the format string used to interpret date strings
(see datestr). If date is a string, but no format is
specified, then a relatively slow search is performed through various
formats. It is always preferable to specify the format string f
if it is known. Formats which do not specify a particular time component
will have the value set to zero. Formats which do not specify a date will
default to January 1st of the current year.
p is the year at the start of the century to which two-digit years will be referenced. If not specified, it defaults to the current year minus 50.
Add q amount of time (with units f) to the serial datenum, d.
f must be one of "year", "month", "day",
"hour", "minute", "second", or
"millisecond".
Return the current monthly calendar in a 6x7 matrix.
If d is specified, return the calendar for the month containing the date d, which must be a serial date number or a date string.
If y and m are specified, return the calendar for year y and month m.
If no output arguments are specified, print the calendar on the screen instead of returning a matrix.
Return the day of the week as a number in n and as a string in s. The days of the week are numbered 1–7 with the first day being Sunday.
d is a serial date number or a date string.
If the string format is not present or is equal to "short" then
s will contain the abbreviated name of the weekday. If format
is "long" then s will contain the full name.
Table of return values based on format:
| n | "short" | "long" |
|---|---|---|
| 1 | Sun | Sunday |
| 2 | Mon | Monday |
| 3 | Tue | Tuesday |
| 4 | Wed | Wednesday |
| 5 | Thu | Thursday |
| 6 | Fri | Friday |
| 7 | Sat | Saturday |
See also: eomday, is_leap_year, calendar, datenum, datevec.
Return the last day of the month m for the year y.
See also: weekday, datenum, datevec, is_leap_year, calendar.
Add date formatted tick labels to an axis. The axis to apply the
ticks to is determined by axis which can take the values "x",
"y", or "z". The default value is "x". The
formatting of the labels is determined by the variable form, which
can either be a string or positive integer that datestr accepts.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave includes many utility functions for copying, moving, renaming, and deleting files; for creating, reading, and deleting directories; for retrieving status information on files; and for manipulating file and path names.
Move the file f1 to the destination f2.
The name f1 may contain globbing patterns. If f1 expands to
multiple file names, f2 must be a directory. If no destination
f2 is specified then the destination is the present working directory.
If f2 is a file name then f1 is renamed to f2.
When the force flag 'f' is given any existing files will be
overwritten without prompting.
If successful, status is 1, and msg, msgid are empty
character strings (""). Otherwise, status is 0, msg contains a
system-dependent error message, and msgid contains a unique message
identifier. Note that the status code is exactly opposite that of the
system command.
Change the name of file old to new.
If successful, err is 0 and msg is an empty string. Otherwise, err is nonzero and msg contains a system-dependent error message.
Copy the file f1 to the destination f2.
The name f1 may contain globbing patterns. If f1 expands to
multiple file names, f2 must be a directory.
when the force flag 'f' is given any existing files will be
overwritten without prompting.
If successful, status is 1, and msg, msgid are empty
character strings (""). Otherwise, status is 0, msg contains a
system-dependent error message, and msgid contains a unique message
identifier. Note that the status code is exactly opposite that of the
system command.
Delete the file named file.
If successful, err is 0 and msg is an empty string. Otherwise, err is nonzero and msg contains a system-dependent error message.
Create a new link (also known as a hard link) to an existing file.
If successful, err is 0 and msg is an empty string. Otherwise, err is nonzero and msg contains a system-dependent error message.
Create a symbolic link new which contains the string old.
If successful, err is 0 and msg is an empty string. Otherwise, err is nonzero and msg contains a system-dependent error message.
Read the value of the symbolic link symlink.
If successful, result contains the contents of the symbolic link symlink, err is 0, and msg is an empty string. Otherwise, err is nonzero and msg contains a system-dependent error message.
Create a directory named dir in the directory parent.
If no parent directory is specified the present working directory is used.
If successful, status is 1, and msg, msgid are empty character strings (""). Otherwise, status is 0, msg contains a system-dependent error message, and msgid contains a unique message identifier.
Remove the directory named dir.
If successful, status is 1, and msg, msgid are empty character strings (""). Otherwise, status is 0, msg contains a system-dependent error message, and msgid contains a unique message identifier.
If the optional second parameter is supplied with value "s",
recursively remove all subdirectories as well.
See also: mkdir, confirm_recursive_rmdir, pwd.
Query or set the internal variable that controls whether Octave will ask for confirmation before recursively removing a directory tree.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: rmdir.
Create a FIFO special file named name with file mode mode
If successful, err is 0 and msg is an empty string. Otherwise, err is nonzero and msg contains a system-dependent error message.
See also: pipe.
Set the permission mask for file creation. The parameter mask is an integer, interpreted as an octal number. If successful, returns the previous value of the mask (as an integer to be interpreted as an octal number); otherwise an error message is printed.
Return a structure info containing the following information about file or file identifier fid.
devID of device containing a directory entry for this file.
inoFile number of the file.
modeFile mode, as an integer. Use the functions S_ISREG,
S_ISDIR, S_ISCHR, S_ISBLK,
S_ISFIFO, S_ISLNK, or S_ISSOCK to extract
information from this value.
modestrFile mode, as a string of ten letters or dashes as would be returned by ls -l.
nlinkNumber of links.
uidUser ID of file’s owner.
gidGroup ID of file’s group.
rdevID of device for block or character special files.
sizeSize in bytes.
atimeTime of last access in the same form as time values returned from
time. See section Timing Utilities.
mtimeTime of last modification in the same form as time values returned from
time. See section Timing Utilities.
ctimeTime of last file status change in the same form as time values
returned from time. See section Timing Utilities.
blksizeSize of blocks in the file.
blocksNumber of blocks allocated for file.
If the call is successful err is 0 and msg is an empty string. If the file does not exist, or some other error occurs, info is an empty matrix, err is -1, and msg contains the corresponding system error message.
If file is a symbolic link, stat will return information
about the actual file that is referenced by the link. Use lstat
if you want information about the symbolic link itself.
For example:
[info, err, msg] = stat ("/vmlinuz")
⇒ info =
{
atime = 855399756
rdev = 0
ctime = 847219094
uid = 0
size = 389218
blksize = 4096
mtime = 847219094
gid = 6
nlink = 1
blocks = 768
mode = -rw-r--r--
modestr = -rw-r--r--
ino = 9316
dev = 2049
}
⇒ err = 0
⇒ msg =
|
Return true if mode corresponds to a block device.
The value of mode is assumed to be returned from a call to stat.
Return true if mode corresponds to a character device.
The value of mode is assumed to be returned from a call to stat.
Return true if mode corresponds to a directory.
The value of mode is assumed to be returned from a call to stat.
Return true if mode corresponds to a fifo.
The value of mode is assumed to be returned from a call to stat.
Return true if mode corresponds to a symbolic link.
The value of mode is assumed to be returned from a call to stat.
Return true if mode corresponds to a regular file.
The value of mode is assumed to be returned from a call to stat.
Return true if mode corresponds to a socket.
The value of mode is assumed to be returned from a call to stat.
Return information about file.
If successful, status is 1, with result containing a structure with the following fields:
NameFull name of file.
archiveTrue if file is an archive (Windows).
systemTrue if file is a system file (Windows).
hiddenTrue if file is a hidden file (Windows).
directoryTrue if file is a directory.
UserReadGroupReadOtherReadTrue if the user (group; other users) has read permission for file.
UserWriteGroupWriteOtherWriteTrue if the user (group; other users) has write permission for file.
UserExecuteGroupExecuteOtherExecuteTrue if the user (group; other users) has execute permission for file.
If an attribute does not apply (i.e., archive on a Unix system) then the field is set to NaN.
With no input arguments, return information about the current directory.
If file contains globbing characters, return information about all the matching files.
See also: glob.
Return true if f is a directory.
See also: exist, stat, is_absolute_filename, is_rooted_relative_filename.
Return the names of files in the directory dir as a cell array of strings.
If an error occurs, return an empty cell array in files. If successful, err is 0 and msg is an empty string. Otherwise, err is nonzero and msg contains a system-dependent error message.
Given an array of pattern strings (as a char array or a cell array) in pattern, return a cell array of file names that match any of them, or an empty cell array if no patterns match. The pattern strings are interpreted as filename globbing patterns (as they are used by Unix shells). Within a pattern
*matches any string, including the null string,
?matches any single character, and
[…]matches any of the enclosed characters.
Tilde expansion is performed on each of the patterns before looking for matching file names. For example:
ls
⇒
file1 file2 file3 myfile1 myfile1b
glob ("*file1")
⇒
{
[1,1] = file1
[2,1] = myfile1
}
glob ("myfile?")
⇒
{
[1,1] = myfile1
}
glob ("file[12]")
⇒
{
[1,1] = file1
[2,1] = file2
}
|
Return true or false for each element of string that matches any of the elements of the string array pattern, using the rules of filename pattern matching. For example:
fnmatch ("a*b", {"ab"; "axyzb"; "xyzab"})
⇒ [ 1; 1; 0 ]
|
Return the absolute name of file if it can be found in
path. The value of path should be a colon-separated list of
directories in the format described for path. If no file
is found, return an empty character string. For example:
file_in_path (EXEC_PATH, "sh")
⇒ "/bin/sh"
|
If the second argument is a cell array of strings, search each directory of the path for element of the cell array and return the first that matches.
If the third optional argument "all" is supplied, return
a cell array containing the list of all files that have the same
name in the path. If no files are found, return an empty cell array.
See also: file_in_loadpath, find_dir_in_path, path.
Return the system-dependent character used to separate directory names.
If "all" is given, the function returns all valid file separators
in the form of a string. The list of file separators is system-dependent.
It is ‘/’ (forward slash) under UNIX or Mac OS X, ‘/’ and
‘\’ (forward and backward slashes) under Windows.
See also: pathsep.
Query or set the character used to separate filename from the the subfunction names contained within the file. This can be used in a generic manner to interact with subfunctions. For example,
help (["myfunc", filemarker, "mysubfunc"]) |
returns the help string associated with the subfunction mysubfunc
of the function myfunc. Another use of filemarker is when
debugging it allows easier placement of breakpoints within subfunctions.
For example,
dbstop (["myfunc", filemarker, "mysubfunc"]) |
will set a breakpoint at the first line of the subfunction mysubfunc.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
Return the directory, name, extension, and version components of filename.
See also: fullfile.
Return a complete filename constructed from the given components.
See also: fileparts.
Perform tilde expansion on string. If string begins with a tilde character, (‘~’), all of the characters preceding the first slash (or all characters, if there is no slash) are treated as a possible user name, and the tilde and the following characters up to the slash are replaced by the home directory of the named user. If the tilde is followed immediately by a slash, the tilde is replaced by the home directory of the user running Octave. For example:
tilde_expand ("~joeuser/bin")
⇒ "/home/joeuser/bin"
tilde_expand ("~/bin")
⇒ "/home/jwe/bin"
|
Return the canonical name of file fname. If the file does not exist the empty string ("") is returned.
See also: make_absolute_filename, is_absolute_filename, is_rooted_relative_filename.
Return the full name of file beginning from the root of the file system. No check is done for the existence of file.
See also: canonicalize_file_name, is_absolute_filename, is_rooted_relative_filename, isdir.
Return true if file is an absolute filename.
See also: is_rooted_relative_filename, make_absolute_filename, isdir.
Return true if file is a rooted-relative filename.
See also: is_absolute_filename, make_absolute_filename, isdir.
Return the default name of the directory for temporary files on this system. The name of this directory is system dependent.
Return the name of the system’s directory for temporary files.
This function is an alias for tmpnam.
See also: tmpnam.
Query or set the preference for recycling deleted files.
Recycling files, instead of permanently deleting them, is not currently implemented in Octave. To help avoid accidental data loss an error will be raised if an attempt is made to enable file recycling.
See also: delete.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Unpack the bzip2 archive bzfile to the directory dir. If dir is not specified, it defaults to the current directory.
Compress the list of files and/or directories specified in files. Each file is compressed separately and a new file with a ‘".gz"’ extension is created. The original files are not modified. Existing compressed files are silently overwritten. If outdir is defined the compressed files are placed in this directory.
Unpack the gzip archive gzfile to the directory dir. If dir is not specified, it defaults to the current directory. If gzfile is a directory, all gzfiles in the directory will be recursively gunzipped.
Pack files files into the TAR archive tarfile. The list of files must be a string or a cell array of strings.
The optional argument root changes the relative path of files from the current directory.
If an output argument is requested the entries in the archive are returned in a cell array.
Unpack the TAR archive tarfile to the directory dir. If dir is not specified, it defaults to the current directory.
Compress the list of files and/or directories specified in files into the archive zipfile in the same directory. If rootdir is defined the files are located relative to rootdir rather than the current directory.
Unpack the ZIP archive zipfile to the directory dir. If dir is not specified, it defaults to the current directory.
Unpack the archive file based on its extension to the directory dir. If file is a list of strings, then each file is unpacked individually. If dir is not specified, it defaults to the current directory. If a directory is in the file list, then the filetype must also be specified.
The optional return value is a list of files unpacked.
Compress the list of files specified in files. Each file is compressed separately and a new file with a ‘".bz2"’ extension is created. The original files are not modified. Existing compressed files are silently overwritten. If outdir is defined the compressed files are placed in this directory.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| 36.4.1 FTP Objects | ||
| 36.4.2 URL Manipulation | ||
| 36.4.3 Base64 and Binary Data Transmission |
Return the hostname of the system where Octave is running.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave supports the FTP protocol through an object-oriented interface.
Use the function ftp to create an FTP object which represents the
connection. All FTP functions take an FTP object as the first argument.
Connect to the FTP server host with username and password.
If username and password are not specified, user
"anonymous" with no password is used. The returned FTP object
f represents the established FTP connection.
The list of actions for an FTP object are shown below. All functions require an FTP object as the first argument.
| Method | Description |
|---|---|
| ascii | Set transfer type to ascii |
| binary | Set transfer type to binary |
| cd | Change remote working directory |
| close | Close FTP connection |
| delete | Delete remote file |
| dir | List remote directory contents |
| mget | Download remote files |
| mkdir | Create remote directory |
| mput | Upload local files |
| rename | Rename remote file or directory |
| rmdir | Remove remote directory |
Close the FTP connection represented by the FTP object f.
f is an FTP object returned by the ftp function.
Download a remote file file or directory dir to the local
directory on the FTP connection f. f is an FTP object
returned by the ftp function.
The arguments file and dir can include wildcards and any files or directories on the remote server that match will be downloaded.
If a third argument target is given, then a single file or directory will be downloaded to the local directory and the local name will be changed to target.
Upload the local file file into the current remote directory on the FTP connection f. f is an FTP object returned by the ftp function.
The argument file is passed through the glob function and any
files that match the wildcards in file will be uploaded.
Get or set the remote directory on the FTP connection f.
f is an FTP object returned by the ftp function.
If path is not specified, return the remote current working directory. Otherwise, set the remote directory to path and return the new remote working directory.
If the directory does not exist, an error message is printed and the working directory is not changed.
List the current directory in verbose form for the FTP connection f.
f is an FTP object returned by the ftp function.
Set the FTP connection f to use ASCII mode for transfers. ASCII mode is only appropriate for text files as it will convert the remote host’s newline representation to the local host’s newline representation.
f is an FTP object returned by the ftp function.
Set the FTP connection f to use binary mode for transfers. In binary mode there is no conversion of newlines from the remote representation to the local representation.
f is an FTP object returned by the ftp function.
Delete the remote file file over the FTP connection f.
f is an FTP object returned by the ftp function.
Rename or move the remote file or directory oldname to newname, over the FTP connection f.
f is an FTP object returned by the ftp function.
Create the remote directory path, over the FTP connection f.
f is an FTP object returned by the ftp function.
Remove the remote directory path, over the FTP connection f.
f is an FTP object returned by the ftp function.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Download a remote file specified by its url and return its content in string s. For example:
s = urlread ("ftp://ftp.octave.org/pub/octave/README");
|
The variable success is 1 if the download was successful, otherwise it is 0 in which case message contains an error message. If no output argument is specified and an error occurs, then the error is signaled through Octave’s error handling mechanism.
This function uses libcurl. Curl supports, among others, the HTTP, FTP and FILE protocols. Username and password may be specified in the URL. For example:
s = urlread ("http://user:password@example.com/file.txt");
|
GET and POST requests can be specified by method and param. The parameter method is either ‘get’ or ‘post’ and param is a cell array of parameter and value pairs. For example:
s = urlread ("http://www.google.com/search", "get",
{"query", "octave"});
|
See also: urlwrite.
Download a remote file specified by its url and save it as localfile. For example:
urlwrite ("ftp://ftp.octave.org/pub/octave/README",
"README.txt");
|
The full path of the downloaded file is returned in f. The variable success is 1 if the download was successful, otherwise it is 0 in which case message contains an error message. If no output argument is specified and an error occurs, then the error is signaled through Octave’s error handling mechanism.
This function uses libcurl. Curl supports, among others, the HTTP, FTP and FILE protocols. Username and password may be specified in the URL, for example:
urlwrite ("http://username:password@example.com/file.txt",
"file.txt");
|
GET and POST requests can be specified by method and param. The parameter method is either ‘get’ or ‘post’ and param is a cell array of parameter and value pairs. For example:
urlwrite ("http://www.google.com/search", "search.html",
"get", {"query", "octave"});
|
See also: urlread.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Some transmission channels can not accept binary data. It is customary to encode binary data in Base64 for transmission and to decode the data upon reception.
Encode a double matrix or array x into the base64 format string s.
See also: base64_decode.
Decode the double matrix or array x from the base64 encoded string s. The optional input parameter dims should be a vector containing the dimensions of the decoded array.
See also: base64_encode.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave includes some high-level commands like system and
popen for starting subprocesses. If you want to run another
program to perform some task and then look at its output, you will
probably want to use these functions.
Octave also provides several very low-level Unix-like functions which can also be used for starting subprocesses, but you should probably only use them if you can’t find any way to do what you need with the higher-level functions.
Execute a shell command specified by string.
If the optional argument type is "async", the process
is started in the background and the process ID of the child process
is returned immediately. Otherwise, the child process is started and
Octave waits until it exits. If the type argument is omitted, it
defaults to the value "sync".
If system is called with one or more output arguments, or if the
optional argument return_output is true and the subprocess is started
synchronously, then the output from the command is returned as a variable.
Otherwise, if the subprocess is executed synchronously, its output is sent
to the standard output. To send the output of a command executed with
system through the pager, use a command like
[output, text] = system ("cmd");
disp (text);
|
or
printf ("%s\n", nthargout (2, "system", "cmd"));
|
The system function can return two values. The first is the
exit status of the command and the second is any output from the
command that was written to the standard output stream. For example,
[status, output] = system ("echo foo; exit 2");
|
will set the variable output to the string ‘foo’, and the
variable status to the integer ‘2’.
For commands run asynchronously, status is the process id of the command shell that is started to run the command.
Execute a system command if running under a Unix-like operating
system, otherwise do nothing. Return the exit status of the program
in status and any output from the command in text.
When called with no output argument, or the "-echo" argument is
given, then text is also sent to standard output.
Execute a system command if running under a Windows-like operating
system, otherwise do nothing. Return the exit status of the program
in status and any output from the command in text.
When called with no output argument, or the "-echo" argument is
given, then text is also sent to standard output.
Invoke Perl script scriptfile, possibly with a list of command line arguments. Return output in output and optional status in status. If scriptfile is not an absolute file name it is is searched for in the current directory and then in the Octave loadpath.
Invoke Python script scriptfile, possibly with a list of command line arguments. Return output in output and optional status in status. If scriptfile is not an absolute file name it is is searched for in the current directory and then in the Octave loadpath.
Start a process and create a pipe. The name of the command to run is given by command. The file identifier corresponding to the input or output stream of the process is returned in fid. The argument mode may be
"r"The pipe will be connected to the standard output of the process, and open for reading.
"w"The pipe will be connected to the standard input of the process, and open for writing.
For example:
fid = popen ("ls -ltr / | tail -3", "r");
while (ischar (s = fgets (fid)))
fputs (stdout, s);
endwhile
-| drwxr-xr-x 33 root root 3072 Feb 15 13:28 etc
-| drwxr-xr-x 3 root root 1024 Feb 15 13:28 lib
-| drwxrwxrwt 15 root root 2048 Feb 17 14:53 tmp
|
Close a file identifier that was opened by popen. You may also
use fclose for the same purpose.
Start a subprocess with two-way communication. The name of the process is given by command, and args is an array of strings containing options for the command. The file identifiers for the input and output streams of the subprocess are returned in in and out. If execution of the command is successful, pid contains the process ID of the subprocess. Otherwise, pid is -1.
For example:
[in, out, pid] = popen2 ("sort", "-r");
fputs (in, "these\nare\nsome\nstrings\n");
fclose (in);
EAGAIN = errno ("EAGAIN");
done = false;
do
s = fgets (out);
if (ischar (s))
fputs (stdout, s);
elseif (errno () == EAGAIN)
sleep (0.1);
fclear (out);
else
done = true;
endif
until (done)
fclose (out);
waitpid (pid);
-| these
-| strings
-| some
-| are
|
Note that popen2, unlike popen, will not "reap" the
child process. If you don’t use waitpid to check the child’s
exit status, it will linger until Octave exits.
Query or set the internal variable that specifies a colon separated
list of directories to append to the shell PATH when executing external
programs. The initial value of is taken from the environment variable
OCTAVE_EXEC_PATH, but that value can be overridden by
the command line argument ‘--exec-path PATH’.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: IMAGE_PATH, OCTAVE_HOME.
In most cases, the following functions simply decode their arguments and
make the corresponding Unix system calls. For a complete example of how
they can be used, look at the definition of the function popen2.
Create a copy of the current process.
Fork can return one of the following values:
You are in the parent process. The value returned from fork is
the process id of the child process. You should probably arrange to
wait for any child processes to exit.
You are in the child process. You can call exec to start another
process. If that fails, you should probably call exit.
The call to fork failed for some reason. You must take evasive
action. A system dependent error message will be waiting in msg.
Replace current process with a new process. Calling exec without
first calling fork will terminate your current Octave process and
replace it with the program named by file. For example,
exec ("ls" "-l")
|
will run ls and return you to your shell prompt.
If successful, exec does not return. If exec does return,
err will be nonzero, and msg will contain a system-dependent
error message.
Create a pipe and return the reading and writing ends of the pipe into read_fd and write_fd respectively.
If successful, err is 0 and msg is an empty string. Otherwise, err is nonzero and msg contains a system-dependent error message.
See also: mkfifo.
Duplicate a file descriptor.
If successful, fid is greater than zero and contains the new file ID. Otherwise, fid is negative and msg contains a system-dependent error message.
Wait for process pid to terminate. The pid argument can be:
Wait for any child process.
Wait for any child process whose process group ID is equal to that of the Octave interpreter process.
Wait for termination of the child process with ID pid.
The options argument can be a bitwise OR of zero or more of the following constants:
0Wait until signal is received or a child process exits (this is the default if the options argument is missing).
WNOHANGDo not hang if status is not immediately available.
WUNTRACEDReport the status of any child processes that are stopped, and whose status has not yet been reported since they stopped.
WCONTINUEReturn if a stopped child has been resumed by delivery of SIGCONT.
This value may not be meaningful on all systems.
If the returned value of pid is greater than 0, it is the process ID of the child process that exited. If an error occurs, pid will be less than zero and msg will contain a system-dependent error message. The value of status contains additional system-dependent information about the subprocess that exited.
See also: WCONTINUE, WCOREDUMP, WEXITSTATUS, WIFCONTINUED, WIFSIGNALED, WIFSTOPPED, WNOHANG, WSTOPSIG, WTERMSIG, WUNTRACED.
Return the numerical value of the option argument that may be
passed to waitpid to indicate that it should also return
if a stopped child has been resumed by delivery of a SIGCONT
signal.
Given status from a call to waitpid, return true if the
child produced a core dump. This function should only be employed if
WIFSIGNALED returned true. The macro used to implement this
function is not specified in POSIX.1-2001 and is not available on some
Unix implementations (e.g., AIX, SunOS).
See also: waitpid, WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WIFSTOPPED, WSTOPSIG, WIFCONTINUED.
Given status from a call to waitpid, return the exit
status of the child. This function should only be employed if
WIFEXITED returned true.
See also: waitpid, WIFEXITED, WIFSIGNALED, WTERMSIG, WCOREDUMP, WIFSTOPPED, WSTOPSIG, WIFCONTINUED.
Given status from a call to waitpid, return true if the
child process was resumed by delivery of SIGCONT.
See also: waitpid, WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WCOREDUMP, WIFSTOPPED, WSTOPSIG.
Given status from a call to waitpid, return true if the
child process was terminated by a signal.
See also: waitpid, WIFEXITED, WEXITSTATUS, WTERMSIG, WCOREDUMP, WIFSTOPPED, WSTOPSIG, WIFCONTINUED.
Given status from a call to waitpid, return true if the
child process was stopped by delivery of a signal; this is only
possible if the call was done using WUNTRACED or when the child
is being traced (see ptrace(2)).
See also: waitpid, WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WCOREDUMP, WSTOPSIG, WIFCONTINUED.
Given status from a call to waitpid, return true if the
child terminated normally.
See also: waitpid, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WCOREDUMP, WIFSTOPPED, WSTOPSIG, WIFCONTINUED.
Return the numerical value of the option argument that may be
passed to waitpid to indicate that it should return its
status immediately instead of waiting for a process to exit.
Given status from a call to waitpid, return the number of
the signal which caused the child to stop. This function should only
be employed if WIFSTOPPED returned true.
See also: waitpid, WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WCOREDUMP, WIFSTOPPED, WIFCONTINUED.
Given status from a call to waitpid, return the number of
the signal that caused the child process to terminate. This function
should only be employed if WIFSIGNALED returned true.
See also: waitpid, WIFEXITED, WEXITSTATUS, WIFSIGNALED, WCOREDUMP, WIFSTOPPED, WSTOPSIG, WIFCONTINUED.
Return the numerical value of the option argument that may be
passed to waitpid to indicate that it should also return
if the child process has stopped but is not traced via the
ptrace system call
Change the properties of the open file fid. The following values may be passed as request:
F_DUPFD
Return a duplicate file descriptor.
F_GETFD
Return the file descriptor flags for fid.
F_SETFD
Set the file descriptor flags for fid.
F_GETFL
Return the file status flags for fid. The following codes may be returned (some of the flags may be undefined on some systems).
O_RDONLY
Open for reading only.
O_WRONLY
Open for writing only.
O_RDWR
Open for reading and writing.
O_APPEND
Append on each write.
O_CREAT
Create the file if it does not exist.
O_NONBLOCK
Non-blocking mode.
O_SYNC
Wait for writes to complete.
O_ASYNC
Asynchronous I/O.
F_SETFL
Set the file status flags for fid to the value specified by
arg. The only flags that can be changed are O_APPEND and
O_NONBLOCK.
If successful, err is 0 and msg is an empty string. Otherwise, err is nonzero and msg contains a system-dependent error message.
Send signal sig to process pid.
If pid is positive, then signal sig is sent to pid.
If pid is 0, then signal sig is sent to every process in the process group of the current process.
If pid is -1, then signal sig is sent to every process except process 1.
If pid is less than -1, then signal sig is sent to every process in the process group -pid.
If sig is 0, then no signal is sent, but error checking is still performed.
Return 0 if successful, otherwise return -1.
Return a structure containing Unix signal names and their defined values.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Return the process group id of the current process.
Return the process id of the current process.
Return the process id of the parent process.
Return the effective user id of the current process.
Return the real user id of the current process.
Return the effective group id of the current process.
Return the real group id of the current process.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Return the value of the environment variable var. For example,
getenv ("PATH")
|
returns a string containing the value of your path.
Set the value of the environment variable var to value.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Change the current working directory to dir.
If dir is omitted, the current directory is changed to the user’s home
directory ("~").
For example,
cd ~/octave |
changes the current working directory to ‘~/octave’. If the directory does not exist, an error message is printed and the working directory is not changed.
chdir is an alias for cd and can be used in all of the same
calling formats.
Compatibility Note: When called with no arguments, MATLAB prints the present working directory rather than changing to the user’s home directory.
List directory contents. For example:
ls -l
-| total 12
-| -rw-r--r-- 1 jwe users 4488 Aug 19 04:02 foo.m
-| -rw-r--r-- 1 jwe users 1315 Aug 17 23:14 bar.m
|
The dir and ls commands are implemented by calling your
system’s directory listing command, so the available options will vary
from system to system.
Filenames are subject to shell expansion if they contain any wildcard characters ‘*’, ‘?’, ‘[]’. If you want to find a literal example of a wildcard character you must escape it using the backslash operator ‘\’.
See also: dir, readdir, glob, what, stat, filesep, ls_command.
Query or set the shell command used by Octave’s ls command.
See also: ls.
Display file listing for directory directory.
If directory is not specified then list the present working directory.
If a return value is requested, return a structure array with the fields
File or directory name.
Timestamp of file modification (string value).
File size in bytes.
True if name is a directory.
Timestamp of file modification as serial date number (double).
Information structure returned from stat.
If directory is a filename, rather than a directory, then return information about the named file. directory may also be a list rather than a single directory or file.
directory is subject to shell expansion if it contains any wildcard characters ‘*’, ‘?’, ‘[]’. If you want to find a literal example of a wildcard character you must escape it using the backslash operator ‘\’.
Note that for symbolic links, dir returns information about
the file that the symbolic link points to rather than the link itself.
However, if the link points to a nonexistent file, dir returns
information about the link.
Return the current working directory.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave’s password database functions return information in a structure with the following fields.
nameThe user name.
passwdThe encrypted password, if available.
uidThe numeric user id.
gidThe numeric group id.
gecosThe GECOS field.
dirThe home directory.
shellThe initial shell.
In the descriptions of the following functions, this data structure is referred to as a pw_struct.
Return a structure containing an entry from the password database,
opening it if necessary. Once the end of the data has been reached,
getpwent returns 0.
Return a structure containing the first entry from the password database
with the user ID uid. If the user ID does not exist in the
database, getpwuid returns 0.
Return a structure containing the first entry from the password database
with the user name name. If the user name does not exist in the
database, getpwname returns 0.
Return the internal pointer to the beginning of the password database.
Close the password database.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave’s group database functions return information in a structure with the following fields.
nameThe user name.
passwdThe encrypted password, if available.
gidThe numeric group id.
memThe members of the group.
In the descriptions of the following functions, this data structure is referred to as a grp_struct.
Return an entry from the group database, opening it if necessary.
Once the end of data has been reached, getgrent returns 0.
Return the first entry from the group database with the group ID
gid. If the group ID does not exist in the database,
getgrgid returns 0.
Return the first entry from the group database with the group name
name. If the group name does not exist in the database,
getgrnam returns 0.
Return the internal pointer to the beginning of the group database.
Close the group database.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Print or return a string of the form cpu-vendor-os that identifies the kind of computer Octave is running on. If invoked with an output argument, the value is returned instead of printed. For example:
computer () -| i586-pc-linux-gnu x = computer () ⇒ x = "i586-pc-linux-gnu" |
If two output arguments are requested, also return the maximum number of elements for an array.
If three output arguments are requested, also return the byte order
of the current system as a character ("B" for big-endian or
"L" for little-endian).
If the argument "arch" is specified, return a string
indicating the architecture of the computer on which Octave is
running.
Return system information in the structure. For example:
uname ()
⇒ {
sysname = x86_64
nodename = segfault
release = 2.6.15-1-amd64-k8-smp
version = Linux
machine = #2 SMP Thu Feb 23 04:57:49 UTC 2006
}
|
If successful, err is 0 and msg is an empty string. Otherwise, err is nonzero and msg contains a system-dependent error message.
Return the current number of available processors.
If called with the optional argument query, modify how processors are counted as follows:
alltotal number of processors.
currentprocessors available to the current process.
overridablelikewise, but overridable through the OMP_NUM_THREADS environment
variable.
Return true if Octave is running on a Windows system and false otherwise.
Return true if Octave is running on a Unix-like system and false otherwise.
Return true if Octave is running on a Mac OS X system and false otherwise.
Return true if your computer claims to conform to the IEEE standard for floating point calculations. No actual tests are performed.
Return true if the current program has been compiled and is running separately from the Octave interpreter and false if it is running in the Octave interpreter. Currently, this function always returns false in Octave.
Return the name of the top-level Octave installation directory.
See also: EXEC_PATH, IMAGE_PATH.
Return the name of the top-level Octave installation directory.
This is an alias for the function OCTAVE_HOME provided
for compatibility.
See also: OCTAVE_HOME.
Return the version number of Octave, as a string.
Return the version number of Octave, as a string.
This is an alias for the function OCTAVE_VERSION provided for
compatibility.
See also: OCTAVE_VERSION.
Display a header containing the current Octave version number, license string, and operating system followed by a list of installed packages, versions, and installation directories.
v = ver ()
Return a vector of structures describing Octave and each installed package. The structure includes the following fields.
NamePackage name.
VersionVersion of the package.
RevisionRevision of the package.
DateDate of the version/revision.
v = ver ("Octave")
Return version information for Octave only.
v = ver (package)
Return version information for package.
See also: version, octave_config_info.
Compare two version strings using the given operator.
This function assumes that versions v1 and v2 are
arbitrarily long strings made of numeric and period characters
possibly followed by an arbitrary string (e.g., "1.2.3",
"0.3", "0.1.2+", or "1.2.3.4-test1").
The version is first split into numeric and character portions
and then the parts are padded to be the same length (i.e., "1.1"
would be padded to be "1.1.0" when being compared with
"1.1.1", and separately, the character parts of the strings are
padded with nulls).
The operator can be any logical operator from the set
"=="
equal
"<"
less than
"<="
less than or equal to
">"
greater than
">="
greater than or equal to
"!="
not equal
"~="
not equal
Note that version "1.1-test2" will compare as greater than
"1.1-test10". Also, since the numeric part is compared first,
"a" compares less than "1a" because the second string
starts with a numeric part even though double ("a") is greater than
double ("1").
Display the license of Octave.
license ("inuse")
Display a list of packages currently being used.
retval = license ("inuse")
Return a structure containing the fields feature and user.
retval = license ("test", feature)
Return 1 if a license exists for the product identified by the string feature and 0 otherwise. The argument feature is case insensitive and only the first 27 characters are checked.
license ("test", feature, toggle)
Enable or disable license testing for feature, depending on toggle, which may be one of:
"enable"Future tests for the specified license of feature are conducted as usual.
"disable"Future tests for the specified license of feature return 0.
retval = license ("checkout", feature)
Check out a license for feature, returning 1 on success and 0 on failure.
This function is provided for compatibility with MATLAB.
Return a structure containing configuration and installation information for Octave.
If option is a string, return the configuration information for the specified option.
Return a structure containing a number of statistics about the current Octave process. Not all fields are available on all systems. If it is not possible to get CPU time statistics, the CPU time slots are set to zero. Other missing data are replaced by NaN. The list of possible fields is:
idrssUnshared data size.
inblockNumber of block input operations.
isrssUnshared stack size.
ixrssShared memory size.
majfltNumber of major page faults.
maxrssMaximum data size.
minfltNumber of minor page faults.
msgrcvNumber of messages received.
msgsndNumber of messages sent.
nivcswNumber of involuntary context switches.
nsignalsNumber of signals received.
nswapNumber of swaps.
nvcswNumber of voluntary context switches.
oublockNumber of block output operations.
stimeA structure containing the system CPU time used. The structure has the
elements sec (seconds) usec (microseconds).
utimeA structure containing the user CPU time used. The structure has the
elements sec (seconds) usec (microseconds).
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
It is often necessary to find if two strings or files are identical. This might be done by comparing them character by character and looking for differences. However, this can be slow, and so comparing a hash of the string or file can be a rapid way of finding if the files differ.
Another use of the hashing function is to check for file integrity. The user can check the hash of the file against a known value and find if the file they have is the same as the one that the original hash was produced with.
Octave supplies the md5sum function to perform MD5 hashes on
strings and files. An example of the use of md5sum function might
be
if exist (file, "file") hash = md5sum (file); else # Treat the variable "file" as a string hash = md5sum (file, true); endif |
Calculate the MD5 sum of the file file. If the second parameter opt exists and is true, then calculate the MD5 sum of the string str.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The Java Interface is designed for calling Java functions from within Octave.
If you want to do the reverse, and call Octave from within Java, try
a library like
javaOctave (http://kenai.com/projects/javaOctave) or
joPas (http://jopas.sourceforge.net).
| 37.1 Java Interface Functions | ||
| 37.2 Dialog Box Functions | ||
| 37.3 FAQ - Frequently asked Questions |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following functions are the core of the Java Interface. They provide a way to create a Java object, get and set its data fields, and call Java methods which return results to Octave.
Create a Java object of class classsname, by calling the class constructor with the arguments arg1, …
The first example below creates an uninitialized object, while the second example supplies an initial argument to the constructor.
x = javaObject ("java.lang.StringBuffer")
x = javaObject ("java.lang.StringBuffer", "Initial string")
|
See also: javaMethod, javaArray.
Create a Java array of size sz with elements of class classname. classname may be a Java object representing a class or a string containing the fully qualified class name. The size of the object may also be specified with individual integer arguments m, n, etc.
The generated array is uninitialized. All elements are set to null if classname is a reference type, or to a default value (usually 0) if classname is a primitive type.
Sample code:
jary = javaArray ("java.lang.String", 2, 2);
jary(1,1) = "Hello";
|
See also: javaObject.
There are many different variable types in Octave but only ones created through
javaObject can use Java functions. Before using Java with an unknown
object the type can be checked with isjava.
Return true if x is a Java object.
See also: class, typeinfo, isa, javaObject.
Once an object has been created it is natural to find out what fields the object has and to read (get) and write (set) them.
In Octave the fieldnames function for structures has been overloaded
to return the fields of a Java object. For example:
dobj = javaObject ("java.lang.Double", pi);
fieldnames (dobj)
⇒
{
[1,1] = public static final double java.lang.Double.POSITIVE_INFINITY
[1,2] = public static final double java.lang.Double.NEGATIVE_INFINITY
[1,3] = public static final double java.lang.Double.NaN
[1,4] = public static final double java.lang.Double.MAX_VALUE
[1,5] = public static final double java.lang.Double.MIN_NORMAL
[1,6] = public static final double java.lang.Double.MIN_VALUE
[1,7] = public static final int java.lang.Double.MAX_EXPONENT
[1,8] = public static final int java.lang.Double.MIN_EXPONENT
[1,9] = public static final int java.lang.Double.SIZE
[1,10] = public static final java.lang.Class java.lang.Double.TYPE
}
|
The analogy of objects with structures is carried over into reading and
writing object fields. To read a field the object is indexed with the
‘.’ operator from structures. This is the preferred method for reading
fields, but Octave also provides a function interface to read fields with
java_get. An example of both styles is shown below.
dobj = javaObject ("java.lang.Double", pi);
dobj.MAX_VALUE
⇒ 1.7977e+308
java_get ("java.lang.Float", "MAX_VALUE")
⇒ 3.4028e+38
|
Get the value of the field name of the Java object obj. For static fields, obj can be a string representing the fully qualified name of the corresponding class.
When obj is a regular Java object, structure-like indexing can be used as a shortcut syntax. For instance, the two following statements are equivalent
java_get (x, "field1") x.field1 |
See also: java_set, javaMethod, javaObject.
Set the value of the field name of the Java object obj to val. For static fields, obj can be a string representing the fully qualified named of the corresponding Java class.
When obj is a regular Java object, structure-like indexing can be used as a shortcut syntax. For instance, the two following statements are equivalent
java_set (x, "field1", val) x.field1 = val |
See also: java_get, javaMethod, javaObject.
To see what functions can be called with an object use methods.
For example, using the previously created dobj:
methods (dobj) ⇒ Methods for class java.lang.Double: boolean equals(java.lang.Object) java.lang.String toString(double) java.lang.String toString() … |
To call a method of an object the same structure indexing operator ‘.’
is used. Octave also provides a functional interface to calling the methods
of an object through javaMethod. An example showing both styles is
shown below.
dobj = javaObject ("java.lang.Double", pi);
dobj.equals (3)
⇒ 0
javaMethod ("equals", dobj, pi)
⇒ 1
|
Invoke the method methodname on the Java object obj with the arguments arg1, … For static methods, obj can be a string representing the fully qualified name of the corresponding class. The function returns the result of the method invocation.
When obj is a regular Java object, structure-like indexing can be used as a shortcut syntax. For instance, the two following statements are equivalent
ret = javaMethod ("method1", x, 1.0, "a string")
ret = x.method1 (1.0, "a string")
|
See also: methods, javaObject.
The following three functions are used to display and modify the class path used by the Java Virtual Machine. This is entirely separate from Octave’s PATH variable and is used by the JVM to find the correct code to execute.
Return the class path of the Java virtual machine in the form of a cell array of strings.
If called with no inputs:
If called with a single input parameter what:
"-dynamic"Return the dynamic classpath.
"-static"Return the static classpath.
"-all"Return both the static and dynamic classpath in a single cellstr.
See also: javaaddpath, javarmpath.
Add clspath to the dynamic class path of the Java virtual machine. clspath may either be a directory where ‘.class’ files are found, or a ‘.jar’ file containing Java classes. Multiple paths may be added at once by specifying additional arguments.
See also: javarmpath, javaclasspath.
Remove clspath from the dynamic class path of the Java virtual machine. clspath may either be a directory where ‘.class’ files are found, or a ‘.jar’ file containing Java classes. Multiple paths may be removed at once by specifying additional arguments.
See also: javaaddpath, javaclasspath.
The following four functions provide information and control over the interface between Octave and the Java Virtual Machine.
Return true if the Java element feature is available.
Possible features are:
"awt"Abstract Window Toolkit for GUIs.
"desktop"Interactive desktop is running.
"jvm"Java Virtual Machine.
"swing"Swing components for lightweight GUIs.
usejava determines if specific Java features are available in an
Octave session. This function is provided for scripts which may alter
their behavior based on the availability of Java. The feature
"desktop" always returns false as Octave has no Java-based
desktop. Other features may be available if Octave was compiled with the
Java Interface and Java is installed.
Show the current memory usage of the Java virtual machine (JVM) and run the garbage collector.
When no return argument is given the info is printed to the screen. Otherwise, the output cell array jmem contains Maximum, Total, and Free memory (in bytes).
All Java-based routines are run in the JVM’s shared memory pool, a dedicated and separate part of memory claimed by the JVM from your computer’s total memory (which comprises physical RAM and virtual memory / swap space on hard disk).
The maximum allowable memory usage can be configured using the file
‘java.opts’. The directory where this file resides is
determined by the environment variable OCTAVE_JAVA_DIR.
If unset, the directory where ‘javaaddpath.m’ resides is used instead
(typically
‘OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/’
‘java.opts’ is a plain text file with one option per line. The default initial memory size and default maximum memory size (which are both system dependent) can be overridden like so:
-Xms64m
-Xmx512m
(in megabytes in this example). You can adapt these values to your own requirements if your system has limited available physical memory or if you get Java memory errors.
"Total memory" is what the operating system has currently assigned to the JVM and depends on actual and active memory usage. "Free memory" is self-explanatory. During operation of Java-based Octave functions the amount of Total and Free memory will vary, due to Java’s own cleaning up and your operating system’s memory management.
Query or set the internal variable that controls whether Java arrays are automatically converted to Octave matrices. The default value is false.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: java_unsigned_autoconversion, debug_java.
Query or set the internal variable that controls how integer classes are
converted when java_matrix_autoconversion is enabled. When enabled,
Java arrays of class Byte or Integer are converted to matrices of class
uint8 or uint32 respectively. The default value is true.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: java_matrix_autoconversion, debug_java.
Query or set the internal variable that determines whether extra debugging information regarding the initialization of the JVM and any Java exceptions is printed.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: java_matrix_autoconversion, java_unsigned_autoconversion.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following functions all use the Java Interface to provide some form of dialog box.
Display msg using a message dialog box.
The message may have multiple lines separated by newline characters
("n"), or it may be a cellstr array with one element for each
line. The optional input title (character string) can be used to
decorate the dialog caption.
The optional argument icon selects a dialog icon.
It can be one of "none" (default), "error",
"help", or "warn".
The return value is always 1.
See also: errordlg, helpdlg, inputdlg, listdlg, questdlg, warndlg.
Display msg using an error dialog box.
The message may have multiple lines separated by newline characters
("\n"), or it may be a cellstr array with one element for each
line. The optional input title (character string) can be used to
set the dialog caption. The default title is "Error Dialog".
The return value is always 1.
See also: helpdlg, inputdlg, listdlg, msgbox, questdlg, warndlg.
Display msg in a help dialog box.
The message may have multiple lines separated by newline characters
("\n"), or it may be a cellstr array with one element for each
line. The optional input title (character string) can be used to
set the dialog caption. The default title is "Help Dialog".
The return value is always 1.
See also: errordlg, inputdlg, listdlg, msgbox, questdlg, warndlg.
Return user input from a multi-textfield dialog box in a cell array of strings, or an empty cell array if the dialog is closed by the Cancel button.
Inputs:
A cell array with strings labeling each text field. This input is required.
String to use for the caption of the dialog. The default is "Input
Dialog".
Specifies the size of the text fields and can take three forms:
A list of default values to place in each text fields. It must be a cell array of strings with the same size as prompt.
See also: errordlg, helpdlg, listdlg, msgbox, questdlg, warndlg.
Return user inputs from a list dialog box in a vector of selection indices sel and a flag ok indicating how the user closed the dialog box. The value of ok is 1 if the user closed the box with the OK button, otherwise it is 0 and sel is empty.
The indices in sel are 1-based.
The arguments are specified in form of key, value pairs.
The "ListString" argument pair must be specified.
Valid key and value pairs are:
"ListString"a cell array of strings comprising the content of the list.
"SelectionMode"can be either "Single" or "Multiple" (default).
"ListSize"a vector with two elements width and height defining the size of the list field in pixels. Default is [160 300].
"InitialValue"a vector containing 1-based indices of preselected elements. Default is 1 (first item).
"Name"a string to be used as the dialog caption. Default is "".
"PromptString"a cell array of strings to be displayed above the list field. Default is {}.
"OKString"a string used to label the OK button. Default is "OK".
"CancelString"a string used to label the Cancel button. Default is "Cancel".
Example:
[sel, ok] = listdlg ("ListString", {"An item", "another", "yet another"},
"SelectionMode", "Multiple");
if (ok == 1)
for i = 1:numel (sel)
disp (sel(i));
endfor
endif
|
See also: menu, errordlg, helpdlg, inputdlg, msgbox, questdlg, warndlg.
Display msg using a question dialog box and return the caption of the activated button.
The dialog may contain two or three buttons which will all close the dialog.
The message may have multiple lines separated by newline characters ("\n"), or it may be a cellstr array with one element for each line. The optional title (character string) can be used to decorate the dialog caption.
The string default identifies the default button, which is activated by pressing the <ENTER> key. It must match one of the strings given in btn1, btn2, or btn3.
If only msg and title are specified, three buttons with
the default captions "Yes", "No", and "Cancel" are
used.
If only two button captions, btn1 and btn2, are specified the dialog will have only these two buttons.
Display msg using a warning dialog box.
The message may have multiple lines separated by newline characters
("\n"), or it may be a cellstr array with one element for each
line. The optional input title (character string) can be used to
set the dialog caption. The default title is "Warning Dialog".
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave and MATLAB are very similar, but handle Java slightly different. Therefore it may be necessary to detect the environment and use the appropriate functions. The following function can be used to detect the environment. Due to the persistent variable it can be called repeatedly without a heavy performance hit.
Example:
%%
%% Return: true if the environment is Octave.
%%
function retval = isOctave
persistent cacheval; % speeds up repeated calls
if isempty (cacheval)
cacheval = (exist ("OCTAVE_VERSION", "builtin") > 0);
end
retval = cacheval;
end
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Java finds classes by searching a classpath. This is a list of Java archive files and/or directories containing class files. In Octave the classpath is composed of two parts:
Octave searches the static classpath first, then the dynamic classpath. Classes appearing in the static as well as in the dynamic classpath will therefore be found in the static classpath and loaded from this location. Classes which will be used frequently or must be available to all users should be added to the static classpath. The static classpath is populated once from the contents of a plain text file named ‘javaclasspath.txt’ (or ‘classpath.txt’ historically) when the Java Virtual Machine starts. This file contains one line for each individual classpath to be added to the static classpath. These lines can identify single class files, directories containing class files, or Java archives with complete class file hierarchies. Comment lines starting with a ‘#’ or a ‘%’ character are ignored.
The search rules for the file ‘javaclasspath.txt’ (or ‘classpath.txt’) are:
OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/’. You can
find this directory by executing the command
which javaclasspath |
If this file exists here, its contents are also appended to the static classpath. Note that the archives and class directories defined in this last step will affect all users.
Classes which are used only by a specific script should be placed in the
dynamic classpath. This portion of the classpath can be modified at
runtime using the javaaddpath and javarmpath functions.
Example:
octave> base_path = "C:/Octave/java_files";
octave> % add two JARchives to the dynamic classpath
octave> javaaddpath ([base_path, "/someclasses.jar"]);
octave> javaaddpath ([base_path, "/moreclasses.jar"]);
octave> % check the dynamic classpath
octave> p = javaclasspath;
octave> disp (p{1});
C:/Octave/java_files/someclasses.jar
octave> disp (p{2});
C:/Octave/java_files/moreclasses.jar
octave> % remove the first element from the classpath
octave> javarmpath ([base_path, "/someclasses.jar"]);
octave> p = javaclasspath;
octave> disp (p{1});
C:/Octave/java_files/moreclasses.jar
octave> % provoke an error
octave> disp (p{2});
error: A(I): Index exceeds matrix dimension.
|
Another way to add files to the dynamic classpath exclusively for your user account is to use the file ‘.octaverc’ which is stored in your home directory. All Octave commands in this file are executed each time you start a new instance of Octave. The following example adds the directory ‘octave’ to Octave’s search path and the archive ‘myclasses.jar’ in this directory to the Java search path.
% contents of .octaverc:
addpath ("~/octave");
javaaddpath ("~/octave/myclasses.jar");
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The function javaObject can be used to create Java objects..
Example:
Passenger = javaObject ("package.FirstClass", row, seat);
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In order to execute Java code Octave creates a Java Virtual Machine (JVM). Such a JVM allocates a fixed amount of initial memory and may expand this pool up to a fixed maximum memory limit. The default values depend on the Java version (see javamem). The memory pool is shared by all Java objects running in the JVM. This strict memory limit is intended mainly to avoid that runaway applications inside web browsers or in enterprise servers can consume all memory and crash the system. When the maximum memory limit is hit, Java code will throw exceptions so that applications will fail or behave unexpectedly.
You can specify options for the creation of the JVM inside a file named ‘java.opts’. This is a text file where you can enter lines containing ‘-X’ and ‘-D’ options handed to the JVM during initialization.
The directory where the Java options file is located is specified by the
environment variable OCTAVE_JAVA_DIR. If unset the directory where
‘javaclasspath.m’ resides is used instead (typically
‘OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/’). You can
find this directory by executing
which javaclasspath |
The ‘-X’ options allow you to increase the maximum amount of memory available to the JVM. The following example allows up to 256 Megabytes to be used by adding the following line to the ‘java.opts’ file:
-Xmx256m |
The maximum possible amount of memory depends on your system. On a Windows system with 2 Gigabytes main memory you should be able to set this maximum to about 1 Gigabyte.
If your application requires a large amount of memory from the beginning, you can also specify the initial amount of memory allocated to the JVM. Adding the following line to the ‘java.opts’ file starts the JVM with 64 Megabytes of initial memory:
-Xms64m |
For more details on the available ‘-X’ options of your Java Virtual Machine issue the command ‘java -X’ at the operating system command prompt and consult the Java documentation.
The ‘-D’ options can be used to define system properties which can then
be used by Java classes inside Octave. System properties can be retrieved by
using the getProperty() methods of the java.lang.System class.
The following example line defines the property MyProperty and assigns it
the string 12.34.
-DMyProperty=12.34 |
The value of this property can then be retrieved as a string by a Java object or in Octave:
octave> javaMethod ("getProperty", "java.lang.System", "MyProperty");
ans = 12.34
|
See also: javamem.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The dialog functions contain a translation table for TeX like symbol codes. Thus messages and labels can be tailored to show some common mathematical symbols or Greek characters. No further TeX formatting codes are supported. The characters are translated to their Unicode equivalent. However, not all characters may be displayable on your system. This depends on the font used by the Java system on your computer.
Each TeX symbol code must be terminated by a space character to make it distinguishable from the surrounding text. Therefore the string ‘\alpha =12.0’ will produce the desired result, whereas ‘\alpha=12.0’ would produce the literal text ’\alpha=12.0’.
See also: errordlg, helpdlg, inputdlg, listdlg, msgbox, questdlg, warndlg.
The table below shows each TeX character code and the corresponding Unicode character:
| \alpha | ’α’ | \beta | ’β’ | \gamma | ’γ’ | ||
| \delta | ’δ’ | \epsilon | ’ε’ | \zeta | ’ζ’ | ||
| \eta | ’η’ | \theta | ’θ’ | \vartheta | ’ϑ’ | ||
| \iota | ’ι’ | \kappa | ’κ’ | \lambda | ’λ’ | ||
| \mu | ’μ’ | \nu | ’ν’ | \xi | ’ξ’ | ||
| \pi | ’π’ | \rho | ’ρ’ | \sigma | ’σ’ | ||
| \varsigma | ’ς’ | \tau | ’τ’ | \phi | ’φ’ | ||
| \chi | ’χ’ | \psi | ’ψ’ | \omega | ’ω’ | ||
| \upsilon | ’υ’ | \Gamma | ’Γ’ | \Delta | ’Δ’ | ||
| \Theta | ’Θ’ | \Lambda | ’Λ’ | \Pi | ’Π’ | ||
| \Xi | ’Ξ’ | \Sigma | ’Σ’ | \Upsilon | ’Υ’ | ||
| \Phi | ’Φ’ | \Psi | ’Ψ’ | \Omega | ’Ω’ | ||
| \Im | ’ℑ’ | \Re | ’ℜ’ | \leq | ’≤’ | ||
| \geq | ’≥’ | \neq | ’≠’ | \pm | ’±’ | ||
| \infty | ’∞’ | \partial | ’∂’ | \approx | ’≈’ | ||
| \circ | ’∘’ | \bullet | ’•’ | \times | ’×’ | ||
| \sim | ’~’ | \nabla | ’∇’ | \ldots | ’…’ | ||
| \exists | ’∃’ | \neg | ’¬’ | \aleph | ’ℵ’ | ||
| \forall | ’∀’ | \cong | ’≅’ | \wp | ’℘’ | ||
| \propto | ’∝’ | \otimes | ’⊗’ | \oplus | ’⊕’ | ||
| \oslash | ’⊘’ | \cap | ’∩’ | \cup | ’∪’ | ||
| \ni | ’∋’ | \in | ’∈’ | \div | ’÷’ | ||
| \equiv | ’≡’ | \int | ’∫’ | \perp | ’⊥’ | ||
| \wedge | ’∧’ | \vee | ’∨’ | \supseteq | ’⊇’ | ||
| \supset | ’⊃’ | \subseteq | ’⊆’ | \subset | ’⊂’ | ||
| \clubsuit | ’♣’ | \spadesuit | ’♠’ | \heartsuit | ’♥’ | ||
| \diamondsuit | ’♦’ | \copyright | ’©’ | \leftarrow | ’←’ | ||
| \uparrow | ’↑’ | \rightarrow | ’→’ | \downarrow | ’↓’ | ||
| \leftrightarrow | ’↔’ | \updownarrow | ’↕’ |
Table: TeX character codes and the resulting symbols.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Since Octave is Free Software users are encouraged to share their programs amongst each other. To aid this sharing Octave supports the installation of extra packages. The ‘Octave-Forge’ project is a community-maintained set of packages that can be downloaded and installed in Octave. At the time of writing the ‘Octave-Forge’ project can be found online at http://octave.sourceforge.net, but since the Internet is an ever-changing place this may not be true at the time of reading. Therefore it is recommended to see the Octave website for an updated reference.
| 38.1 Installing and Removing Packages | ||
| 38.2 Using Packages | ||
| 38.3 Administrating Packages | ||
| 38.4 Creating Packages |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Assuming a package is available in the file ‘image-1.0.0.tar.gz’ it can be installed from the Octave prompt with the command
pkg install image-1.0.0.tar.gz |
If the package is installed successfully nothing will be printed on
the prompt, but if an error occurred during installation it will be
reported. It is possible to install several packages at once by
writing several package files after the pkg install command.
If a different version of the package is already installed it will
be removed prior to installing the new package. This makes it easy to
upgrade and downgrade the version of a package, but makes it
impossible to have several versions of the same package installed at
once.
To see which packages are installed type
pkg list -| Package Name | Version | Installation directory -| --------------+---------+----------------------- -| image *| 1.0.0 | /home/jwe/octave/image-1.0.0 |
In this case only version 1.0.0 of the image package is
installed. The '*' character next to the package name shows that the
image package is loaded and ready for use.
It is possible to remove a package from the system using the
pkg uninstall command like this
pkg uninstall image |
If the package is removed successfully nothing will be printed in the
prompt, but if an error occurred it will be reported. It should be
noted that the package file used for installation is not needed for
removal, and that only the package name as reported by pkg list
should be used when removing a package. It is possible to remove
several packages at once by writing several package names after the
pkg uninstall command.
To minimize the amount of code duplication between packages it is
possible that one package depends on another one. If a package
depends on another, it will check if that package is installed
during installation. If it is not, an error will be reported and
the package will not be installed. This behavior can be disabled
by passing the ‘-nodeps’ flag to the pkg install
command
pkg install -nodeps my_package_with_dependencies.tar.gz |
Since the installed package expects its dependencies to be installed it may not function correctly. Because of this it is not recommended to disable dependency checking.
Manage packages (groups of add-on functions) for Octave. Different actions are available depending on the value of command.
Available commands:
Install named packages. For example,
pkg install image-1.0.0.tar.gz |
installs the package found in the file ‘image-1.0.0.tar.gz’.
The option variable can contain options that affect the manner in which a package is installed. These options can be one or more of
-nodepsThe package manager will disable dependency checking. With this option it is possible to install a package even when it depends on another package which is not installed on the system. Use this option with care.
-noautoThe package manager will not automatically load the installed package when starting Octave. This overrides any setting within the package.
-autoThe package manager will automatically load the installed package when starting Octave. This overrides any setting within the package.
-localA local installation (package available only to current user) is forced, even if the user has system privileges.
-globalA global installation (package available to all users) is forced, even if the user doesn’t normally have system privileges.
-forgeInstall a package directly from the Octave-Forge repository. This requires an internet connection and the cURL library.
-verboseThe package manager will print the output of all commands as they are performed.
Check installed Octave-Forge packages against repository and update any outdated items. This requires an internet connection and the cURL library. Usage:
pkg update |
Uninstall named packages. For example,
pkg uninstall image |
removes the image package from the system. If another installed
package depends on the image package an error will be issued.
The package can be uninstalled anyway by using the ‘-nodeps’ option.
Add named packages to the path. After loading a package it is possible to use the functions provided by the package. For example,
pkg load image |
adds the image package to the path. It is possible to load all
installed packages at once with the keyword ‘all’. Usage:
pkg load all |
Remove named packages from the path. After unloading a package it is no longer possible to use the functions provided by the package. It is possible to unload all installed packages at once with the keyword ‘all’. Usage:
pkg unload all |
Show the list of currently installed packages. For example,
installed_packages = pkg ("list")
|
returns a cell array containing a structure for each installed package.
If two output arguments are requested pkg splits the list of
installed packages into those which were installed by the current user,
and those which were installed by the system administrator.
[user_packages, system_packages] = pkg ("list")
|
The option "-forge" lists packages available at the Octave-Forge
repository. This requires an internet connection and the cURL library.
For example:
oct_forge_pkgs = pkg ("list", "-forge")
|
Show a short description of the named installed packages, with the option
"-verbose" also list functions provided by the package. For example,
pkg describe -verbose all |
will describe all installed packages and the functions they provide. If one output is requested a cell of structure containing the description and list of functions of each package is returned as output rather than printed on screen:
desc = pkg ("describe", "secs1d", "image")
|
If any of the requested packages is not installed, pkg returns an error, unless a second output is requested:
[desc, flag] = pkg ("describe", "secs1d", "image")
|
flag will take one of the values "Not installed",
"Loaded", or
"Not loaded" for each of the named packages.
Set the installation prefix directory. For example,
pkg prefix ~/my_octave_packages |
sets the installation prefix to ‘~/my_octave_packages’. Packages will be installed in this directory.
It is possible to get the current installation prefix by requesting an output argument. For example:
pfx = pkg ("prefix")
|
The location in which to install the architecture dependent files can be independently specified with an addition argument. For example:
pkg prefix ~/my_octave_packages ~/my_arch_dep_pkgs |
Set the file in which to look for information on locally installed packages. Locally installed packages are those that are available only to the current user. For example:
pkg local_list ~/.octave_packages |
It is possible to get the current value of local_list with the following
pkg local_list |
Set the file in which to look for information on globally installed packages. Globally installed packages are those that are available to all users. For example:
pkg global_list /usr/share/octave/octave_packages |
It is possible to get the current value of global_list with the following
pkg global_list |
Build a binary form of a package or packages. The binary file produced
will itself be an Octave package that can be installed normally with
pkg. The form of the command to build a binary package is
pkg build builddir image-1.0.0.tar.gz … |
where builddir is the name of a directory where the temporary
installation will be produced and the binary packages will be found.
The options ‘-verbose’ and ‘-nodeps’ are respected, while
all other options are ignored.
Rebuild the package database from the installed directories. This can be used in cases where the package database has been corrupted. It can also take the ‘-auto’ and ‘-noauto’ options to allow the autoloading state of a package to be changed. For example,
pkg rebuild -noauto image |
will remove the autoloading status of the image package.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
By default installed packages are not available from the Octave prompt,
but it is possible to control this using the pkg load and
pkg unload commands. The functions from a package can be
added to the Octave path by typing
pkg load package_name |
where package_name is the name of the package to be added
to the path.
In much the same way a package can be removed from the Octave path by typing
pkg unload package_name |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
On UNIX-like systems it is possible to make both per-user and
system-wide installations of a package. If the user performing the
installation is root the packages will be installed in a
system-wide directory that defaults to
‘OCTAVE_HOME/share/octave/packages/’. If the user is not
root the default installation directory is
‘~/octave/’. Packages will be installed in a subdirectory of the
installation directory that will be named after the package. It is
possible to change the installation directory by using the
pkg prefix command
pkg prefix new_installation_directory |
The current installation directory can be retrieved by typing
current_installation_directory = pkg prefix |
To function properly the package manager needs to keep some
information about the installed packages. For per-user packages this
information is by default stored in the file ‘~/.octave_packages’
and for system-wide installations it is stored in
‘OCTAVE_HOME/share/octave/octave_packages’. The path to the
per-user file can be changed with the pkg local_list command
pkg local_list /path/to/new_file |
For system-wide installations this can be changed in the same way
using the pkg global_list command. If these commands are
called without a new path, the current path will be returned.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Internally a package is simply a gzipped tar file that contains a
top level directory of any given name. This directory will in the
following be referred to as package and may contain the
following files:
package/CITATIONThis is am optional file describing instructions on how to cite
the package for publication. It will be displayed verbatim by the
function citation.
package/COPYINGThis is a required file containing the license of the package. No restrictions is made on the license in general. If however the package contains dynamically linked functions the license must be compatible with the GNU General Public License.
package/DESCRIPTIONThis is a required file containing information about the package. See section The DESCRIPTION File, for details on this file.
package/ChangeLogThis is an optional file describing all the changes made to the package source files.
package/INDEXThis is an optional file describing the functions provided by the
package. If this file is not given then one with be created
automatically from the functions in the package and the
Categories keyword in the ‘DESCRIPTION’ file.
See section The INDEX File, for details on this file.
package/NEWSThis is an optional file describing all user-visible changes worth mentioning. As this file increases on size, old entries can be moved into ‘package/ONEWS’.
package/ONEWSThis is an optional file describing old entries from the ‘NEWS’ file.
package/PKG_ADDAn optional file that includes commands that are run when the package
is added to the users path. Note that PKG_ADD directives in the
source code of the package will also be added to this file by the
Octave package manager. Note that symbolic links are to be avoided in
packages, as symbolic links do not exist on some file systems, and so
a typical use for this file is the replacement of the symbolic link
ln -s foo.oct bar.oct |
with an autoload directive like
autoload ('bar', which ('foo'));
|
See section PKG_ADD and PKG_DEL Directives, for details on PKG_ADD
directives.
package/PKG_DELAn optional file that includes commands that are run when the package
is removed from the users path. Note that PKG_DEL directives in
the source code of the package will also be added to this file by the
Octave package manager.
See section PKG_ADD and PKG_DEL Directives, for details on PKG_DEL
directives.
package/pre_install.mThis is an optional function that is run prior to the installation of a package. This function is called with a single argument, a struct with fields names after the data in the ‘DESCRIPTION’, and the paths where the package functions will be installed.
package/post_install.mThis is an optional function that is run after the installation of a package. This function is called with a single argument, a struct with fields names after the data in the ‘DESCRIPTION’, and the paths where the package functions were installed.
package/on_uninstall.mThis is an optional function that is run prior to the removal of a package. This function is called with a single argument, a struct with fields names after the data in the ‘DESCRIPTION’, the paths where the package functions are installed, and whether the package is currently loaded.
Besides the above mentioned files, a package can also contain one or more of the following directories:
package/instAn optional directory containing any files that are directly installed
by the package. Typically this will include any m-files.
package/srcAn optional directory containing code that must be built prior to the
packages installation. The Octave package manager will execute
‘./configure’ in this directory if this script exists, and will
then call make if a file ‘Makefile’ exists in this
directory. make install will however not be called. The
environment variables MKOCTFILE, OCTAVE_CONFIG, and
OCTAVE will be set to the full paths of the programs
mkoctfile, octave-config, and octave, respectively,
of the correct version when configure and make are
called. If a file called FILES exists all files listed there
will be copied to the inst directory, so they also will be
installed. If the FILES file doesn’t exist, ‘src/*.m’ and
‘src/*.oct’ will be copied to the inst directory.
package/docAn optional directory containing documentation for the package. The files in this directory will be directly installed in a sub-directory of the installed package for future reference.
package/binAn optional directory containing files that will be added to the
Octave EXEC_PATH when the package is loaded. This might contain
external scripts, etc., called by functions within the package.
| 38.4.1 The DESCRIPTION File | ||
| 38.4.2 The INDEX File | ||
| 38.4.3 PKG_ADD and PKG_DEL Directives | ||
| 38.4.4 Missing Components |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The ‘DESCRIPTION’ file contains various information about the package, such as its name, author, and version. This file has a very simple format
NameOfOption: ValueOfOption.
The following is a simple example of a ‘DESCRIPTION’ file
Name: The name of my package Version: 1.0.0 Date: 2007-18-04 Author: The name (and possibly email) of the package author. Maintainer: The name (and possibly email) of the current package maintainer. Title: The title of the package Description: A short description of the package. If this description gets too long for one line it can continue on the next by adding a space to the beginning of the following lines. License: GPLv3+ |
The package manager currently recognizes the following keywords
NameName of the package.
VersionVersion of the package. A package version must be 3 numbers separated by dots.
DateDate of last update.
AuthorOriginal author of the package.
MaintainerMaintainer of the package.
TitleA one line description of the package.
DescriptionA one paragraph description of the package.
CategoriesOptional keyword describing the package (if no ‘INDEX’ file is given this is mandatory).
ProblemsOptional list of known problems.
UrlOptional list of homepages related to the package.
AutoloadOptional field that sets the default loading behavior for the package.
If set to yes, true or on, then Octave will
automatically load the package when starting. Otherwise the package
must be manually loaded with the pkg load command. This default
behavior can be overridden when the package is installed.
DependsA list of other Octave packages that this package depends on. This can include dependencies on particular versions, with a format
Depends: package (>= 1.0.0) |
Possible operators are <, <=, ==, >= or
>. If the part of the dependency in () is missing, any
version of the package is acceptable. Multiple dependencies can be
defined either as a comma separated list or on separate Depends
lines.
LicenseAn optional short description of the used license (e.g., GPL version 3 or newer). This is optional since the file ‘COPYING’ is mandatory.
SystemRequirementsThese are the external install dependencies of the package and are not
checked by the package manager. This is here as a hint to the
distribution packager. They follow the same conventions as the
Depends keyword.
BuildRequiresThese are the external build dependencies of the package and are not
checked by the package manager. This is here as a hint to the
distribution packager. They follow the same conventions as the
Depends keyword. Note that in general, packaging systems such
as rpm or deb and autoprobe the install dependencies
from the build dependencies, and therefore the often a
BuildRequires dependency removes the need for a
SystemRequirements dependency.
The developer is free to add additional arguments to the
‘DESCRIPTION’ file for their own purposes. One further detail to
aid the packager is that the SystemRequirements and
BuildRequires keywords can have a distribution dependent section,
and the automatic build process will use these. An example of the
format of this is
BuildRequires: libtermcap-devel [Mandriva] libtermcap2-devel |
where the first package name will be used as a default and if the RPMs are built on a Mandriva distribution, then the second package name will be used instead.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The optional ‘INDEX’ file provides a categorical view of the functions in the package. This file has a very simple format
toolbox >> Toolbox name |
The format can be summarized with the following example:
# A comment toolbox >> Toolbox name Category Name 1 function1 function2 function3 function4 Category Name 2 function2 function5 |
If you wish to refer to a function that users might expect to find in your package but is not there, providing a work around or pointing out that the function is available elsewhere, you can use:
fn = workaround description |
This workaround description will not appear when listing functions in the
package with pkg describe but they will be published
in the HTML documentation online.
Workaround descriptions can use any HTML markup, but
keep in mind that it will be enclosed in a bold-italic environment.
For the special case of:
fn = use <code>alternate expression</code> |
the bold-italic is automatically suppressed. You will need
to use <code> even in references:
fn = use <a href="someothersite.html"><code>fn</code></a> |
Sometimes functions are only partially compatible, in which
case you can list the non-compatible cases separately. To
refer to another function in the package, use <f>fn</f>.
For example:
eig (a, b) = use <f>qz</f> |
Since sites may have many missing functions, you can define a macro rather than typing the same link over and again.
$id = expansion |
defines the macro id. You can use $id anywhere in the
description and it will be expanded. For example:
$TSA = see <a href="link_to_spctools">SPC Tools</a> arcov = $TSA <code>armcv</code> |
id is any string of letters, numbers and _.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
If the package contains files called PKG_ADD or PKG_DEL
the commands in these files will be executed when the package is
added or removed from the users path. In some situations such files
are a bit cumbersome to maintain, so the package manager supports
automatic creation of such files. If a source file in the package
contains a PKG_ADD or PKG_DEL directive they will be
added to either the PKG_ADD or PKG_DEL files.
In m-files a PKG_ADD directive looks like this
## PKG_ADD: some_octave_command |
Such lines should be added before the function keyword.
In C++ files a PKG_ADD directive looks like this
// PKG_ADD: some_octave_command |
In both cases some_octave_command should be replaced by the
command that should be placed in the PKG_ADD file.
PKG_DEL directives work in the same way, except the
PKG_ADD keyword is replaced with PKG_DEL and the commands
get added to the PKG_DEL file.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
If a package relies on a component, such as another Octave package, that may
not be present it may be useful to install a function which informs users what
to do when a particular component is missing. The function must be written by
the package maintainer and registered with Octave using
missing_component_hook.
Query or set the internal variable that specifies the function to call when a component of Octave is missing. This can be useful for packagers that may split the Octave installation into multiple sub-packages, for example, to provide a hint to users for how to install the missing components.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
The hook function is expected to be of the form
fcn (component) |
Octave will call fcn with the name of the function that requires the component and a string describing the missing component. The hook function should return an error message to be displayed.
See also: missing_function_hook.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
"The sum of human wisdom is not contained in any one language" —Ezra Pound
Octave is a fantastic language for solving many problems in science and
engineering. However, it is not the only computer language and there
are times when you may want to use code written in other languages.
Good reasons for doing so include: 1) not re-inventing the wheel; existing
function libraries which have been thoroughly tested and debugged or
large scale simulation codebases are a good example, 2) accessing unique
capabilities of a different language; for example the well-known regular
expression functions of Perl (but don’t do that because regexp
already exists in Octave).
Performance should generally not be a reason for using compiled extensions. Although compiled extensions can run faster, particularly if they replace a loop in Octave code, this is almost never the best path to take. First, there are many techniques to speed up Octave performance while remaining within the language. Second, Octave is a high-level language that makes it easy to perform common mathematical tasks. Giving that up means shifting the focus from solving the real problem to solving a computer programming problem. It means returning to low-level constructs such as pointers, memory management, mathematical overflow/underflow, etc. Because of the low level nature, and the fact that the compiled code is executed outside of Octave, there is the very real possibility of crashing the interpreter and losing work.
Before going further, you should first determine if you really need to bother writing code outside of Octave.
Even when a function already exists outside the language, it may be better to simply reproduce the behavior in an m-file rather than attempt to interface to the outside code.
If performance is an issue you should always start with the in-language techniques for getting better performance. Chief among these is vectorization (see section Vectorization and Faster Code Execution) which not only makes the code concise and more understandable but improves performance (10X-100X). If loops must be used, make sure that the allocation of space for variables takes place outside the loops using an assignment to a matrix of the right size, or zeros.
These routines are highly optimized and many do not carry the overhead of being interpreted.
It will take time to learn Octave’s interface for external code and there will inevitably be issues with tools such as compilers.
With that said, Octave offers a versatile interface for including chunks
of compiled code as dynamically linked extensions. These dynamically linked
functions can be called from the interpreter in the same manner as any
ordinary function. The interface is bi-directional and external code can
call Octave functions (like plot) which otherwise might be very
difficult to develop.
The interface is centered around supporting the languages C++, C, and Fortran. Octave itself is written in C++ and can call external C++/C code through its native oct-file interface. The C language is also supported through the mex-file interface for compatibility with MATLAB. Fortran code is easiest to reach through the oct-file interface.
Because many other languages provide C or C++ APIs it is relatively simple to build bridges between Octave and other languages. This is also a way to bridge to hardware resources which often have device drivers written in C.
| A.1 Oct-Files | ||
| A.2 Mex-Files | ||
| A.3 Standalone Programs |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Oct-files are pieces of C++ code that have been compiled with the Octave API into a dynamically loadable object. They take their name from the file which contains the object which has the extension ‘.oct’.
Finding a C++ compiler, using the correct switches, adding the right include
paths for header files, etc. is a difficult task. Octave automates this by
providing the mkoctfile command with which to build oct-files. The
command is available from within Octave or at the shell command line.
The mkoctfile function compiles source code written in C,
C++, or Fortran. Depending on the options used with mkoctfile, the
compiled code can be called within Octave or can be used as a stand-alone
application.
mkoctfile can be called from the shell prompt or from the Octave
prompt. Calling it from the Octave prompt simply delegates the
call to the shell prompt. The output is stored in the output
variable and the exit status in the status variable.
mkoctfile accepts the following options, all of which are optional
except for the file name of the code you wish to compile:
Add the include directory DIR to compile commands.
Add the definition DEF to the compiler call.
Add the library LIB to the link command.
Add the library directory DIR to the link command.
Generate dependency files (.d) for C and C++ source files.
Add the run-time path to the link command.
Pass flags though the linker like "-Wl,-rpath=…". The quotes are needed since commas are interpreted as command separators.
Pass flags though the compiler like "-Wa,OPTION".
Compile but do not link.
Enable debugging options for compilers.
Output file name. Default extension is .oct (or .mex if ‘--mex’ is specified) unless linking a stand-alone executable.
Print the configuration variable VAR. Recognized variables are:
ALL_CFLAGS INCFLAGS ALL_CXXFLAGS INCLUDEDIR ALL_FFLAGS LAPACK_LIBS ALL_LDFLAGS LD_CXX AR LDFLAGS BLAS_LIBS LD_STATIC_FLAG CC LFLAGS CFLAGS LIBDIR CPICFLAG LIBOCTAVE CPPFLAGS LIBOCTINTERP CXX LIBS CXXFLAGS OCTAVE_HOME CXXPICFLAG OCTAVE_LIBS DEPEND_EXTRA_SED_PATTERN OCTAVE_LINK_DEPS DEPEND_FLAGS OCTAVE_LINK_OPTS DL_LD OCTAVE_PREFIX DL_LDFLAGS OCTINCLUDEDIR F77 OCTLIBDIR F77_INTEGER8_FLAG OCT_LINK_DEPS FFLAGS OCT_LINK_OPTS FFTW3F_LDFLAGS RANLIB FFTW3F_LIBS RDYNAMIC_FLAG FFTW3_LDFLAGS READLINE_LIBS FFTW3_LIBS SED FFTW_LIBS SPECIAL_MATH_LIB FLIBS XTRA_CFLAGS FPICFLAG XTRA_CXXFLAGS |
Link a stand-alone executable file.
Assume we are creating a MEX file. Set the default output extension to ".mex".
Strip the output file.
Echo commands as they are executed.
The file to compile or link. Recognized file types are
.c C source .cc C++ source .C C++ source .cpp C++ source .f Fortran source (fixed form) .F Fortran source (fixed form) .f90 Fortran source (free form) .F90 Fortran source (free form) .o object file .a library file |
Consider the following short example which introduces the basics of writing a C++ function that can be linked to Octave.
#include <octave/oct.h>
DEFUN_DLD (helloworld, args, nargout,
"Hello World Help String")
{
int nargin = args.length ();
octave_stdout << "Hello World has "
<< nargin << " input arguments and "
<< nargout << " output arguments.\n";
return octave_value_list ();
}
|
The first critical line is #include <octave/oct.h> which
makes available most of the definitions necessary for a C++ oct-file.
Note that ‘octave/oct.h’ is a C++ header and cannot be directly
#include’ed in a C source file, nor any other language.
Included by ‘oct.h’ is a definition for the macro
DEFUN_DLD which creates a dynamically loaded function. This
macro takes four arguments:
octave_value_list,
The return type of functions defined with DEFUN_DLD is always
octave_value_list.
There are a couple of important considerations in the choice of function
name. First, it must be a valid Octave function name and so must be a
sequence of letters, digits, and underscores not starting with a
digit. Second, as Octave uses the function name to define the filename
it attempts to find the function in, the function name in the
DEFUN_DLD macro must match the filename of the oct-file. Therefore,
the above function should be in a file ‘helloworld.cc’, and would be
compiled to an oct-file using the command
mkoctfile helloworld.cc |
This will create a file called ‘helloworld.oct’ that is the compiled
version of the function. It should be noted that it is perfectly
acceptable to have more than one DEFUN_DLD function in a source
file. However, there must either be a symbolic link to the oct-file for
each of the functions defined in the source code with the DEFUN_DLD
macro or the autoload (Function Files) function should be used.
The rest of the function shows how to find the number of input arguments, how to print through the Octave pager, and return from the function. After compiling this function as above, an example of its use is
helloworld (1, 2, 3) -| Hello World has 3 input arguments and 0 output arguments. |
Subsequent sections show how to use specific classes from Octave’s core internals. Base classes like dMatrix (a matrix of double values) are found in the directory ‘liboctave/array’. The definitive reference for how to use a particular class is the header file itself. However, it is often enough just to study the examples in the manual in order to be able to use the class.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave supports a number of different array and matrix classes, the majority of which are based on the Array class. The exception is the sparse matrix types discussed separately below. There are three basic matrix types
MatrixA double precision matrix class defined in ‘dMatrix.h’,
ComplexMatrixA complex matrix class defined in ‘CMatrix.h’, and
BoolMatrixA boolean matrix class defined in ‘boolMatrix.h’.
These are the basic two-dimensional matrix types of Octave. In addition there are a number of multi-dimensional array types including
NDArrayA double precision array class defined in ‘dNDArray.h’
ComplexNDarrayA complex array class defined in ‘CNDArray.h’
boolNDArrayA boolean array class defined in ‘boolNDArray.h’
int8NDArrayint16NDArrayint32NDArrayint64NDArray8, 16, 32, and 64-bit signed array classes defined in ‘int8NDArray.h’, ‘int16NDArray.h’, etc.
uint8NDArrayuint16NDArrayuint32NDArrayuint64NDArray8, 16, 32, and 64-bit unsigned array classes defined in ‘uint8NDArray.h’, ‘uint16NDArray.h’, etc.
There are several basic ways of constructing matrices or
multi-dimensional arrays. Using the class Matrix as an example
one can
Matrix a; |
This can be used for all matrix and array types.
size. For example:
dim_vector dv (2); dv(0) = 2; dv(1) = 3; // 2 rows, 3 columns Matrix a (dv); |
This can be used on all matrix and array types.
Matrix a (2, 2) |
However, this constructor can only be used with matrix types.
These types all share a number of basic methods and operators. Many bear a resemblance to functions that exist in the interpreter. A selection of useful methods include
The () operator or elem method allow the values of the
matrix or array to be read or set. These can take a single argument,
which is of type octave_idx_type, that is the index into the matrix or
array. Additionally, the matrix type allows two argument versions of the
() operator and elem method, giving the row and column index of the
value to obtain or set.
Note that these functions do significant error checking and so in some circumstances the user might prefer to access the data of the array or matrix directly through the fortran_vec method discussed below.
The total number of elements in the matrix or array.
The number of bytes used to store the matrix or array.
The dimensions of the matrix or array in value of type dim_vector.
The number of dimensions of the matrix or array. Matrices are 2-D, but arrays can be N-dimensional.
A method taking either an argument of type dim_vector, or in the
case of a matrix two arguments of type octave_idx_type defining
the number of rows and columns in the matrix.
This method returns a pointer to the underlying data of the matrix or array so that it can be manipulated directly, either within Octave or by an external library.
Operators such an +, -, or * can be used on the
majority of the matrix and array types. In addition there are a number of
methods that are of interest only for matrices such as transpose,
hermitian, solve, etc.
The typical way to extract a matrix or array from the input arguments of
DEFUN_DLD function is as follows
#include <octave/oct.h>
DEFUN_DLD (addtwomatrices, args, , "Add A to B")
{
int nargin = args.length ();
if (nargin != 2)
print_usage ();
else
{
NDArray A = args(0).array_value ();
NDArray B = args(1).array_value ();
if (! error_state)
return octave_value (A + B);
}
return octave_value_list ();
}
|
To avoid segmentation faults causing Octave to abort this function
explicitly checks that there are sufficient arguments available before
accessing these arguments. It then obtains two multi-dimensional arrays
of type NDArray and adds these together. Note that the array_value
method is called without using the is_matrix_type type, and instead the
error_state is checked before returning A + B. The reason to
prefer this is that the arguments might be a type that is not an
NDArray, but it would make sense to convert it to one. The
array_value method allows this conversion to be performed
transparently if possible, and sets error_state if it is not.
A + B, operating on two NDArray’s returns an
NDArray, which is cast to an octave_value on the return
from the function. An example of the use of this demonstration function is
addtwomatrices (ones (2, 2), eye (2, 2))
⇒ 2 1
1 2
|
A list of the basic Matrix and Array types, the methods to
extract these from an octave_value, and the associated header file is
listed below.
| Type | Function | Source Code |
|---|---|---|
RowVector | row_vector_value | ‘dRowVector.h’ |
ComplexRowVector | complex_row_vector_value | ‘CRowVector.h’ |
ColumnVector | column_vector_value | ‘dColVector.h’ |
ComplexColumnVector | complex_column_vector_value | ‘CColVector.h’ |
Matrix | matrix_value | ‘dMatrix.h’ |
ComplexMatrix | complex_matrix_value | ‘CMatrix.h’ |
boolMatrix | bool_matrix_value | ‘boolMatrix.h’ |
charMatrix | char_matrix_value | ‘chMatrix.h’ |
NDArray | array_value | ‘dNDArray.h’ |
ComplexNDArray | complex_array_value | ‘CNDArray.h’ |
boolNDArray | bool_array_value | ‘boolNDArray.h’ |
charNDArray | char_array_value | ‘charNDArray.h’ |
int8NDArray | int8_array_value | ‘int8NDArray.h’ |
int16NDArray | int16_array_value | ‘int16NDArray.h’ |
int32NDArray | int32_array_value | ‘int32NDArray.h’ |
int64NDArray | int64_array_value | ‘int64NDArray.h’ |
uint8NDArray | uint8_array_value | ‘uint8NDArray.h’ |
uint16NDArray | uint16_array_value | ‘uint16NDArray.h’ |
uint32NDArray | uint32_array_value | ‘uint32NDArray.h’ |
uint64NDArray | uint64_array_value | ‘uint64NDArray.h’ |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A character string in Octave is just a special Array class.
Consider the example:
#include <octave/oct.h>
DEFUN_DLD (stringdemo, args, , "String Demo")
{
octave_value_list retval;
int nargin = args.length ();
if (nargin != 1)
print_usage ();
else
{
charMatrix ch = args(0).char_matrix_value ();
if (! error_state)
{
retval(1) = octave_value (ch, '\''); // Single Quote String
octave_idx_type nr = ch.rows ();
for (octave_idx_type i = 0; i < nr / 2; i++)
{
std::string tmp = ch.row_as_string (i);
ch.insert (ch.row_as_string (nr-i-1).c_str (), i, 0);
ch.insert (tmp.c_str (), nr-i-1, 0);
}
retval(0) = octave_value (ch, '"'); // Double Quote String
}
}
return retval;
}
|
An example of the use of this function is
s0 = ["First String"; "Second String"];
[s1,s2] = stringdemo (s0)
⇒ s1 = Second String
First String
⇒ s2 = First String
Second String
typeinfo (s2)
⇒ sq_string
typeinfo (s1)
⇒ string
|
One additional complication of strings in Octave is the difference
between single quoted and double quoted strings. To find out if an
octave_value contains a single or double quoted string use
one of the predicate tests shown below.
if (args(0).is_sq_string ()) octave_stdout << "First argument is a single quoted string\n"; else if (args(0).is_dq_string ()) octave_stdout << "First argument is a double quoted string\n"; |
Note, however, that both types of strings are represented by the
charNDArray type, and so when assigning to an
octave_value, the type of string should be specified. For example:
octave_value_list retval;
charNDArray ch;
…
// Create single quoted string
retval(1) = octave_value (ch); // default constructor is sq_string
OR
retval(1) = octave_value (ch, '\''); // explicitly create sq_string
// Create a double quoted string
retval(0) = octave_value (ch, '"');
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave’s cell type is also available from within oct-files. A cell
array is just an array of octave_values, and thus each element of the
cell array can be treated just like any other octave_value. A simple
example is
#include <octave/oct.h>
#include <octave/Cell.h>
DEFUN_DLD (celldemo, args, , "Cell Demo")
{
octave_value_list retval;
int nargin = args.length ();
if (nargin != 1)
print_usage ();
else
{
Cell c = args(0).cell_value ();
if (! error_state)
for (octave_idx_type i = 0; i < c.numel (); i++)
{
retval(i) = c(i); // using operator syntax
//retval(i) = c.elem (i); // using method syntax
}
}
return retval;
}
|
Note that cell arrays are used less often in standard oct-files and so
the ‘Cell.h’ header file must be explicitly included. The rest of the
example extracts the octave_values one by one from the cell array and
returns them as individual return arguments. For example:
[b1, b2, b3] = celldemo ({1, [1, 2], "test"})
⇒
b1 = 1
b2 =
1 2
b3 = test
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A structure in Octave is a map between a number of fields represented and
their values. The Standard Template Library map class is used,
with the pair consisting of a std::string and an Octave
Cell variable.
A simple example demonstrating the use of structures within oct-files is
#include <octave/oct.h>
#include <octave/ov-struct.h>
DEFUN_DLD (structdemo, args, , "Struct Demo")
{
octave_value retval;
int nargin = args.length ();
if (args.length () == 2)
{
octave_scalar_map arg0 = args(0).scalar_map_value ();
//octave_map arg0 = args(0).map_value ();
if (! error_state)
{
std::string arg1 = args(1).string_value ();
if (! error_state)
{
octave_value tmp = arg0.contents (arg1);
//octave_value tmp = arg0.contents (arg1)(0);
if (tmp.is_defined ())
{
octave_scalar_map st;
st.assign ("selected", tmp);
retval = octave_value (st);
}
else
error ("structdemo: struct does not have a field named '%s'\n",
arg1.c_str ());
}
else
error ("structdemo: ARG2 must be a character string");
}
else
error ("structdemo: ARG1 must be a struct");
}
else
print_usage ();
return retval;
}
|
An example of its use is
x.a = 1; x.b = "test"; x.c = [1, 2]; structdemo (x, "b") ⇒ selected = test |
The example above specifically uses the octave_scalar_map class which
is for representing a single struct. For structure arrays the
octave_map class is used instead. The commented code shows how the
demo could be modified to handle a structure array. In that case the
contents method returns a Cell which may have more than one
element. Therefore, to obtain the underlying octave_value in
this single-struct example we write
octave_value tmp = arg0.contents (arg1)(0); |
where the trailing (0) is the () operator on the Cell object. If
this were a true structure array with multiple elements we could iterate
over the elements using the () operator.
Structures are a relatively complex data container and there are more
functions available in ‘oct-map.h’ which make coding with them easier
than relying on just contents.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There are three classes of sparse objects that are of interest to the user.
SparseMatrixA double precision sparse matrix class
SparseComplexMatrixA complex sparse matrix class
SparseBoolMatrixA boolean sparse matrix class
All of these classes inherit from the Sparse<T> template class,
and so all have similar capabilities and usage. The Sparse<T>
class was based on Octave’s Array<T> class, and so users familiar
with Octave’s Array classes will be comfortable with the use of
the sparse classes.
The sparse classes will not be entirely described in this section, due
to their similarity with the existing Array classes. However,
there are a few differences due the different nature of sparse objects,
and these will be described. First, although it is fundamentally
possible to have N-dimensional sparse objects, the Octave sparse classes do
not allow them at this time; All instances of the sparse classes
must be 2-dimensional. This means that SparseMatrix is actually
more similar to Octave’s Matrix class than its NDArray class.
| A.1.6.1 Array and Sparse Class Differences | ||
| A.1.6.2 Creating Sparse Matrices in Oct-Files | ||
| A.1.6.3 Using Sparse Matrices in Oct-Files |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The number of elements in a sparse matrix is considered to be the number of non-zero elements rather than the product of the dimensions. Therefore
SparseMatrix sm; … int nel = sm.nelem (); |
returns the number of non-zero elements. If the user really requires the
number of elements in the matrix, including the non-zero elements, they
should use numel rather than nelem. Note that for very
large matrices, where the product of the two dimensions is larger than
the representation of an unsigned int, then numel can overflow.
An example is speye (1e6) which will create a matrix with a million
rows and columns, but only a million non-zero elements. Therefore the
number of rows by the number of columns in this case is more than two
hundred times the maximum value that can be represented by an unsigned int.
The use of numel should therefore be avoided useless it is known
it won’t overflow.
Extreme care must be take with the elem method and the "()" operator,
which perform basically the same function. The reason is that if a
sparse object is non-const, then Octave will assume that a
request for a zero element in a sparse matrix is in fact a request
to create this element so it can be filled. Therefore a piece of
code like
SparseMatrix sm;
…
for (int j = 0; j < nc; j++)
for (int i = 0; i < nr; i++)
std::cerr << " (" << i << "," << j << "): " << sm(i,j) << std::endl;
|
is a great way of turning the sparse matrix into a dense one, and a very slow way at that since it reallocates the sparse object at each zero element in the matrix.
An easy way of preventing the above from happening is to create a temporary constant version of the sparse matrix. Note that only the container for the sparse matrix will be copied, while the actual representation of the data will be shared between the two versions of the sparse matrix. So this is not a costly operation. For example, the above would become
SparseMatrix sm;
…
const SparseMatrix tmp (sm);
for (int j = 0; j < nc; j++)
for (int i = 0; i < nr; i++)
std::cerr << " (" << i << "," << j << "): " << tmp(i,j) << std::endl;
|
Finally, as the sparse types aren’t represented by a contiguous
block of memory, the fortran_vec method of the Array<T>
is not available. It is, however, replaced by three separate methods
ridx, cidx and data, that access the raw compressed
column format that Octave sparse matrices are stored in. These methods can be
used in a manner similar to elem to allow the matrix to be accessed or
filled. However, in that case it is up to the user to respect the sparse
matrix compressed column format.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There are several useful alternatives for creating a sparse matrix. The first is to create three vectors representing the row index, column index, and data values, and from these create the matrix. The second alternative is to create a sparse matrix with the appropriate amount of space and then fill in the values. Both techniques have their advantages and disadvantages.
Below is an example of creating a small sparse matrix using the first technique
int nz, nr, nc; nz = 4, nr = 3, nc = 4; ColumnVector ridx (nz); ColumnVector cidx (nz); ColumnVector data (nz); ridx(0) = 1; cidx(0) = 1; data(0) = 1; ridx(1) = 2; cidx(1) = 2; data(1) = 2; ridx(2) = 2; cidx(2) = 4; data(2) = 3; ridx(3) = 3; cidx(3) = 4; data(3) = 4; SparseMatrix sm (data, ridx, cidx, nr, nc); |
which creates the matrix given in section Storage of Sparse Matrices. Note that the compressed matrix format is not used at the time of the creation of the matrix itself, but is used internally.
As discussed in the chapter on Sparse Matrices, the values of the sparse matrix are stored in increasing column-major ordering. Although the data passed by the user need not respect this requirement, pre-sorting the data will significantly speed up creation of the sparse matrix.
The disadvantage of this technique for creating a sparse matrix is that there is a brief time when two copies of the data exist. For extremely memory constrained problems this may not be the best technique for creating a sparse matrix.
The alternative is to first create a sparse matrix with the desired number of non-zero elements and then later fill those elements in. Sample code:
int nz, nr, nc; nz = 4, nr = 3, nc = 4; SparseMatrix sm (nr, nc, nz); sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4; |
This creates the same matrix as previously. Again, although not strictly necessary, it is significantly faster if the sparse matrix is created and the elements are added in column-major ordering. The reason for this is that when elements are inserted at the end of the current list of known elements then no element in the matrix needs to be moved to allow the new element to be inserted; Only the column indexes need to be updated.
There are a few further points to note about this method of creating a sparse matrix. First, it is possible to create a sparse matrix with fewer elements than are actually inserted in the matrix. Therefore,
int nr, nc; nr = 3, nc = 4; SparseMatrix sm (nr, nc, 0); sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4; |
is perfectly valid. However, it is a very bad idea because as each new element is added to the sparse matrix the matrix needs to request more space and reallocate memory. This is an expensive operation, that will significantly slow this means of creating a sparse matrix. Furthermore, it is possible to create a sparse matrix with too much storage, so having nz greater than 4 is also valid. The disadvantage is that the matrix occupies more memory than strictly needed.
It is not always possible to know the number of non-zero elements prior
to filling a matrix. For this reason the additional unused storage of
a sparse matrix can be removed after its creation with the
maybe_compress function. In addition, maybe_compress can
deallocate the unused storage, but it can also remove zero elements
from the matrix. The removal of zero elements from the matrix is
controlled by setting the argument of the maybe_compress function
to be true. However, the cost of removing the zeros is high because it
implies re-sorting the elements. If possible, it is better
if the user does not add the unnecessary zeros in the first place.
An example of the use of maybe_compress is
int nz, nr, nc; nz = 6, nr = 3, nc = 4; SparseMatrix sm1 (nr, nc, nz); sm1(0,0) = 1; sm1(0,1) = 2; sm1(1,3) = 3; sm1(2,3) = 4; sm1.maybe_compress (); // No zero elements were added SparseMatrix sm2 (nr, nc, nz); sm2(0,0) = 1; sm2(0,1) = 2; sm(0,2) = 0; sm(1,2) = 0; sm1(1,3) = 3; sm1(2,3) = 4; sm2.maybe_compress (true); // Zero elements were added |
The use of the maybe_compress function should be avoided if
possible as it will slow the creation of the matrix.
A third means of creating a sparse matrix is to work directly with the data in compressed row format. An example of this technique might be
octave_value arg;
…
int nz, nr, nc;
nz = 6, nr = 3, nc = 4; // Assume we know the max # nz
SparseMatrix sm (nr, nc, nz);
Matrix m = arg.matrix_value ();
int ii = 0;
sm.cidx (0) = 0;
for (int j = 1; j < nc; j++)
{
for (int i = 0; i < nr; i++)
{
double tmp = foo (m(i,j));
if (tmp != 0.)
{
sm.data(ii) = tmp;
sm.ridx(ii) = i;
ii++;
}
}
sm.cidx(j+1) = ii;
}
sm.maybe_compress (); // If don't know a priori the final # of nz.
|
which is probably the most efficient means of creating a sparse matrix.
Finally, it might sometimes arise that the amount of storage initially
created is insufficient to completely store the sparse matrix. Therefore,
the method change_capacity exists to reallocate the sparse memory.
The above example would then be modified as
octave_value arg;
…
int nz, nr, nc;
nz = 6, nr = 3, nc = 4; // Assume we know the max # nz
SparseMatrix sm (nr, nc, nz);
Matrix m = arg.matrix_value ();
int ii = 0;
sm.cidx (0) = 0;
for (int j = 1; j < nc; j++)
{
for (int i = 0; i < nr; i++)
{
double tmp = foo (m(i,j));
if (tmp != 0.)
{
if (ii == nz)
{
nz += 2; // Add 2 more elements
sm.change_capacity (nz);
}
sm.data(ii) = tmp;
sm.ridx(ii) = i;
ii++;
}
}
sm.cidx(j+1) = ii;
}
sm.maybe_mutate (); // If don't know a priori the final # of nz.
|
Note that both increasing and decreasing the number of non-zero elements in a sparse matrix is expensive as it involves memory reallocation. Also as parts of the matrix, though not its entirety, exist as old and new copies at the same time, additional memory is needed. Therefore, if possible this should be avoided.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Most of the same operators and functions on sparse matrices that are
available from the Octave command line are also available within oct-files.
The basic means of extracting a sparse matrix from an octave_value
and returning it as an octave_value, can be seen in the
following example.
octave_value_list retval;
SparseMatrix sm = args(0).sparse_matrix_value ();
SparseComplexMatrix scm =
args(1).sparse_complex_matrix_value ();
SparseBoolMatrix sbm = args(2).sparse_bool_matrix_value ();
…
retval(2) = sbm;
retval(1) = scm;
retval(0) = sm;
|
The conversion to an octave_value is handled by the sparse
octave_value constructors, and so no special care is needed.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Global variables allow variables in the global scope to be
accessed. Global variables can be accessed within oct-files by using
the support functions get_global_value and set_global_value.
get_global_value takes two arguments, the first is a string representing
the variable name to obtain. The second argument is a boolean argument
specifying what to do if no global variable of the desired name is found.
An example of the use of these two functions is
#include <octave/oct.h>
DEFUN_DLD (globaldemo, args, , "Global Demo")
{
octave_value retval;
int nargin = args.length ();
if (nargin != 1)
print_usage ();
else
{
std::string s = args(0).string_value ();
if (! error_state)
{
octave_value tmp = get_global_value (s, true);
if (tmp.is_defined ())
retval = tmp;
else
retval = "Global variable not found";
set_global_value ("a", 42.0);
}
}
return retval;
}
|
An example of its use is
global a b
b = 10;
globaldemo ("b")
⇒ 10
globaldemo ("c")
⇒ "Global variable not found"
num2str (a)
⇒ 42
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
There is often a need to be able to call another Octave function from
within an oct-file, and there are many examples of such within Octave
itself. For example, the quad function is an oct-file that
calculates the definite integral by quadrature over a user supplied
function.
There are also many ways in which a function might be passed. It might be passed as one of
The example below demonstrates an example that accepts all four means of passing a function to an oct-file.
#include <octave/oct.h>
#include <octave/parse.h>
DEFUN_DLD (funcdemo, args, nargout, "Function Demo")
{
octave_value_list retval;
int nargin = args.length ();
if (nargin < 2)
print_usage ();
else
{
octave_value_list newargs;
for (octave_idx_type i = nargin - 1; i > 0; i--)
newargs(i-1) = args(i);
if (args(0).is_function_handle () || args(0).is_inline_function ())
{
octave_function *fcn = args(0).function_value ();
if (! error_state)
retval = feval (fcn, newargs, nargout);
}
else if (args(0).is_string ())
{
std::string fcn = args(0).string_value ();
if (! error_state)
retval = feval (fcn, newargs, nargout);
}
else
error ("funcdemo: INPUT must be string, inline, or function handle");
}
return retval;
}
|
The first argument to this demonstration is the user-supplied function and the remaining arguments are all passed to the user function.
funcdemo (@sin,1)
⇒ 0.84147
funcdemo (@(x) sin (x), 1)
⇒ 0.84147
funcdemo (inline ("sin (x)"), 1)
⇒ 0.84147
funcdemo ("sin",1)
⇒ 0.84147
funcdemo (@atan2, 1, 1)
⇒ 0.78540
|
When the user function is passed as a string the treatment of the
function is different. In some cases it is necessary to have the
user supplied function as an octave_function object. In that
case the string argument can be used to create a temporary function
as demonstrated below.
std::octave fcn_name = unique_symbol_name ("__fcn__");
std::string fcode = "function y = ";
fcode.append (fcn_name);
fcode.append ("(x) y = ");
fcn = extract_function (args(0), "funcdemo", fcn_name,
fcode, "; endfunction");
…
if (fcn_name.length ())
clear_function (fcn_name);
|
There are two important things to know in this case. First, the number of input arguments to the user function is fixed, and in the above example is a single argument. Second, to avoid leaving the temporary function in the Octave symbol table it should be cleared after use. Also, by convention internal function names begin and end with the character sequence ‘__’.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Linking external C code to Octave is relatively simple, as the C functions can easily be called directly from C++. One possible issue is that the declarations of the external C functions may need to be explicitly defined as C functions to the compiler. If the declarations of the external C functions are in the header ‘foo.h’, then the tactic to ensure that the C++ compiler treats these declarations as C code is
#ifdef __cplusplus
extern "C"
{
#endif
#include "foo.h"
#ifdef __cplusplus
} /* end extern "C" */
#endif
|
Calling Fortran code, however, can pose more difficulties. This is due to differences in the manner in which compilers treat the linking of Fortran code with C or C++ code. Octave supplies a number of macros that allow consistent behavior across a number of compilers.
The underlying Fortran code should use the XSTOPX function to
replace the Fortran STOP function. XSTOPX uses the Octave
exception handler to treat failing cases in the Fortran code
explicitly. Note that Octave supplies its own replacement BLAS
XERBLA function, which uses XSTOPX.
If the code calls XSTOPX, then the F77_XFCN
macro should be used to call the underlying Fortran function. The Fortran
exception state can then be checked with the global variable
f77_exception_encountered. If XSTOPX will not be called,
then the F77_FCN macro should be used instead to call the Fortran
code.
There is no great harm in using F77_XFCN in all cases, except that
for Fortran code that is short running and executes a large number of times,
there is potentially an overhead in doing so. However, if F77_FCN
is used with code that calls XSTOP, Octave can generate a
segmentation fault.
An example of the inclusion of a Fortran function in an oct-file is given in the following example, where the C++ wrapper is
#include <octave/oct.h>
#include <octave/f77-fcn.h>
extern "C"
{
F77_RET_T
F77_FUNC (fortransub, FORTSUB)
(const int&, double*, F77_CHAR_ARG_DECL F77_CHAR_ARG_LEN_DECL);
}
DEFUN_DLD (fortrandemo, args, , "Fortran Demo")
{
octave_value_list retval;
int nargin = args.length ();
if (nargin != 1)
print_usage ();
else
{
NDArray a = args(0).array_value ();
if (! error_state)
{
double *av = a.fortran_vec ();
octave_idx_type na = a.numel ();
OCTAVE_LOCAL_BUFFER (char, ctmp, 128);
F77_XFCN (fortransub, FORTSUB,
(na, av, ctmp F77_CHAR_ARG_LEN (128)));
retval(1) = std::string (ctmp);
retval(0) = a;
}
}
return retval;
}
|
and the Fortran function is
subroutine fortransub (n, a, s)
implicit none
character*(*) s
real*8 a(*)
integer*4 i, n, ioerr
do i = 1, n
if (a(i) .eq. 0d0) then
call xstopx ('fortransub: divide by zero')
else
a(i) = 1d0 / a(i)
endif
enddo
write (unit = s, fmt = '(a,i3,a,a)', iostat = ioerr)
$ 'There are ', n,
$ ' values in the input vector', char(0)
if (ioerr .ne. 0) then
call xstopx ('fortransub: error writing string')
endif
return
end
|
This example demonstrates most of the features needed to link to an external Fortran function, including passing arrays and strings, as well as exception handling. Both the Fortran and C++ files need to be compiled in order for the example to work.
mkoctfile fortrandemo.cc fortransub.f [b, s] = fortrandemo (1:3) ⇒ b = 1.00000 0.50000 0.33333 s = There are 3 values in the input vector [b, s] = fortrandemo (0:3) error: fortrandemo: fortransub: divide by zero |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Allocating memory within an oct-file might seem easy as the C++
new/delete operators can be used. However, in that case great care must be
taken to avoid memory leaks. The preferred manner in which to allocate
memory for use locally is to use the OCTAVE_LOCAL_BUFFER macro.
An example of its use is
OCTAVE_LOCAL_BUFFER (double, tmp, len) |
that returns a pointer tmp of type double * of length
len.
In this case Octave itself will worry about reference counting and variable scope and will properly free memory without programmer intervention.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
As oct-files are compiled functions they open up the possibility of crashing Octave through careless function calls or memory faults. It is quite important that each and every function have a sufficient level of parameter checking to ensure that Octave behaves well.
The minimum requirement, as previously discussed, is to check the number of input arguments before using them to avoid referencing a non-existent argument. However, in some cases this might not be sufficient as the underlying code imposes further constraints. For example, an external function call might be undefined if the input arguments are not integers, or if one of the arguments is zero, or if the input is complex and a real value was expected. Therefore, oct-files often need additional input parameter checking.
There are several functions within Octave that can be useful for the
purposes of parameter checking. These include the methods of the
octave_value class like is_real_matrix, is_numeric_type, etc.
Often, with a knowledge of the Octave m-file language, you can guess at what
the corresponding C++ routine will. In addition there are some more
specialized input validation functions of which a few are demonstrated below.
#include <octave/oct.h>
DEFUN_DLD (paramdemo, args, nargout, "Parameter Check Demo")
{
octave_value retval;
int nargin = args.length ();
if (nargin != 1)
print_usage ();
else if (nargout != 0)
error ("paramdemo: OUTPUT argument required");
else
{
NDArray m = args(0).array_value ();
double min_val = -10.0;
double max_val = 10.0;
octave_stdout << "Properties of input array:\n";
if (m.any_element_is_negative ())
octave_stdout << " includes negative values\n";
if (m.any_element_is_inf_or_nan ())
octave_stdout << " includes Inf or NaN values\n";
if (m.any_element_not_one_or_zero ())
octave_stdout << " includes other values than 1 and 0\n";
if (m.all_elements_are_int_or_inf_or_nan ())
octave_stdout << " includes only int, Inf or NaN values\n";
if (m.all_integers (min_val, max_val))
octave_stdout << " includes only integers in [-10,10]\n";
}
return retval;
}
|
An example of its use is:
paramdemo ([1, 2, NaN, Inf])
⇒ Properties of input array:
includes Inf or NaN values
includes other values than 1 and 0
includes only int, Inf or NaN values
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Another important feature of Octave is its ability to react to the user
typing <Control-C> even during calculations. This ability is based on the
C++ exception handler, where memory allocated by the C++ new/delete
methods are automatically released when the exception is treated. When
writing an oct-file, to allow Octave to treat the user typing <Control-C>,
the OCTAVE_QUIT macro is supplied. For example:
for (octave_idx_type i = 0; i < a.nelem (); i++)
{
OCTAVE_QUIT;
b.elem (i) = 2. * a.elem (i);
}
|
The presence of the OCTAVE_QUIT macro in the inner loop allows
Octave to treat the user request with the <Control-C>. Without this macro,
the user must either wait for the function to return before the interrupt is
processed, or press <Control-C> three times to force Octave to exit.
The OCTAVE_QUIT macro does impose a very small speed penalty, and so
for loops that are known to be small it might not make sense to include
OCTAVE_QUIT.
When creating an oct-file that uses an external libraries, the function
might spend a significant portion of its time in the external
library. It is not generally possible to use the OCTAVE_QUIT macro
in this case. The alternative in this case is
BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE; … some code that calls a "foreign" function … END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE; |
The disadvantage of this is that if the foreign code allocates any
memory internally, then this memory might be lost during an interrupt,
without being deallocated. Therefore, ideally Octave itself should
allocate any memory that is needed by the foreign code, with either the
fortran_vec method or the OCTAVE_LOCAL_BUFFER macro.
The Octave unwind_protect mechanism (The unwind_protect Statement) can also be used in oct-files. In conjunction with the exception handling of Octave, it is important to enforce that certain code is run to allow variables, etc. to be restored even if an exception occurs. An example of the use of this mechanism is
#include <octave/oct.h>
#include <octave/unwind-prot.h>
void
my_err_handler (const char *fmt, ...)
{
// Do nothing!!
}
DEFUN_DLD (unwinddemo, args, nargout, "Unwind Demo")
{
octave_value retval;
int nargin = args.length ();
if (nargin < 2)
print_usage ();
else
{
NDArray a = args(0).array_value ();
NDArray b = args(1).array_value ();
if (! error_state)
{
// Declare unwind_protect frame which lasts as long as
// the variable frame has scope.
unwind_protect frame;
frame.protect_var (current_liboctave_warning_handler);
set_liboctave_warning_handler (my_err_handler);
retval = octave_value (quotient (a, b));
}
}
return retval;
}
|
As can be seen in the example:
unwinddemo (1, 0) ⇒ Inf 1 / 0 ⇒ warning: division by zero Inf |
The warning for division by zero (and in fact all warnings) are disabled in the
unwinddemo function.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The documentation of an oct-file is the fourth string parameter of the
DEFUN_DLD macro. This string can be formatted in the same manner
as the help strings for user functions (see section Tips for Documentation Strings),
however there are some issue that are particular to the formatting of
help strings within oct-files.
The major issue is that the help string will typically be longer than a single line of text, and so the formatting of long help strings needs to be taken into account. There are several possible solutions, but the most common is illustrated in the following example,
DEFUN_DLD (do_what_i_want, args, nargout,
"-*- texinfo -*-\n\
@deftypefn {Function File} {} do_what_i_say (@var{n})\n\
A function that does what the user actually wants rather\n\
than what they requested.\n\
@end deftypefn")
{
…
}
|
where, as can be seen, each line of text is terminated by \n\
which is an embedded new-line in the string together with a C++ string
continuation character. Note that the final \ must be the last
character on the line.
Octave also includes the ability to embed test and demonstration
code for a function within the code itself (see section Test and Demo Functions).
This can be used from within oct-files (or in fact any file) with
certain provisos. First, the test and demo functions of Octave look
for %! as the first two characters of a line to identify test
and demonstration code. This is a requirement for oct-files as well.
In addition, the test and demonstration code must be wrapped in a comment
block to avoid it being interpreted by the compiler. Finally, the Octave
test and demonstration code must have access to the original source code
of the oct-file and not just the compiled code as the tests are stripped
from the compiled code. An example in an oct-file might be
/* %!assert (sin ([1,2]), [sin(1),sin(2)]) %!error (sin ()) %!error (sin (1,1)) */ |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave includes an interface to allow legacy mex-files to be compiled and used with Octave. This interface can also be used to share code between Octave and MATLAB users. However, as mex-files expose MATLAB’s internal API, and the internal structure of Octave is different, a mex-file can never have the same performance in Octave as the equivalent oct-file. In particular, to support the manner in which variables are passed to mex functions there are a significant number of additional copies of memory blocks when calling or returning from a mex-file function. For this reason, it is recommended that any new code be written with the oct-file interface previously discussed.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The basic command to build a mex-file is either mkoctfile --mex
or mex. The first command can be used either from within Octave or from
the command line. However, to avoid issues with MATLAB’s own mex
command, the use of the command mex is limited to within Octave.
Compiled mex-files have the extension ‘.mex’.
Compile source code written in C, C++, or Fortran, to a MEX file.
This is equivalent to mkoctfile --mex [options] file.
See also: mkoctfile.
Return the filename extension used for MEX files.
See also: mex.
Consider the following short example:
#include "mex.h"
void
mexFunction (int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
mexPrintf ("Hello, World!\n");
mexPrintf ("I have %d inputs and %d outputs\n", nrhs, nlhs);
}
|
The first line #include "mex.h" makes available all of the definitions
necessary for a mex-file. One important difference between Octave and
MATLAB is that the header file "matrix.h" is implicitly included
through the inclusion of "mex.h". This is necessary to avoid a conflict
with the Octave file "Matrix.h" for operating systems and compilers that
don’t distinguish between filenames in upper and lower case.
The entry point into the mex-file is defined by mexFunction. The
function takes four arguments:
Note that the function name definition is not explicitly included in
mexFunction and so there can only be a single mexFunction
entry point per file. Instead, the name of the function as seen in Octave is
determined by the name of the mex-file itself minus the extension. Therefore,
if the above function is in the file ‘myhello.c’, it can be compiled with
mkoctfile --mex myhello.c |
which creates a file ‘myhello.mex’. The function can then be run from Octave as
myhello (1,2,3) ⇒ Hello, World! ⇒ I have 3 inputs and 0 outputs |
It should be noted that the mex-file contains no help string for the functions it contains. To document mex-files, there should exist an m-file in the same directory as the mex-file itself. Taking the above as an example, we would therefore have a file ‘myhello.m’ that might contain the text
%MYHELLO Simple test of the functionality of a mex-file. |
In this case, the function that will be executed within Octave will be given by the mex-file, while the help string will come from the m-file. This can also be useful to allow a sample implementation of the mex-file within the Octave language itself for testing purposes.
Although there cannot be multiple entry points in a single mex-file,
one can use the mexFunctionName function to determine what name
the mex-file was called with. This can be used to alter the behavior of
the mex-file based on the function name. For example, if
#include "mex.h"
void
mexFunction (int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
const char *nm;
nm = mexFunctionName ();
mexPrintf ("You called function: %s\n", nm);
if (strcmp (nm, "myfunc") == 0)
mexPrintf ("This is the principal function\n", nm);
return;
}
|
is in file ‘myfunc.c’, and it is compiled with
mkoctfile --mex myfunc.c ln -s myfunc.mex myfunc2.mex |
then as can be seen by
myfunc ()
⇒ You called function: myfunc
This is the principal function
myfunc2 ()
⇒ You called function: myfunc2
|
the behavior of the mex-file can be altered depending on the functions name.
Although the user should only include ‘mex.h’ in their code, Octave declares additional functions, typedefs, etc., available to the user to write mex-files in the headers ‘mexproto.h’ and ‘mxarray.h’.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The basic mex type of all variables is mxArray. Any object,
such as a matrix, cell array, or structure is stored in this basic
type. As such, mxArray serves basically the same purpose as the
octave_value class in oct-files in that it acts as a container for the
more specialized types.
The mxArray structure contains at a minimum, the name of the
variable it represents, its dimensions, its type, and whether the variable is
real or complex. It can also contain a number of additional fields
depending on the type of the mxArray. There are a number of
functions to create mxArray structures, including
mxCreateDoubleMatrix, mxCreateCellArray, mxCreateSparse,
and the generic mxCreateNumericArray.
The basic function to access the data contained in an array is
mxGetPr. As the mex interface assumes that real and imaginary
parts of a complex array are stored separately, there is an equivalent
function mxGetPi that gets the imaginary part. Both of these
functions are only for use with double precision matrices. The generic
functions mxGetData and mxGetImagData perform the same operation
on all matrix types. For example:
mxArray *m; mwSize *dims; UINT32_T *pr; dims = (mwSize *) mxMalloc (2 * sizeof (mwSize)); dims[0] = 2; dims[1] = 2; m = mxCreateNumericArray (2, dims, mxUINT32_CLASS, mxREAL); pr = (UINT32_T *) mxGetData (m); |
There are also the functions mxSetPr, etc., that perform the
inverse, and set the data of an array to use the block of memory pointed
to by the argument of mxSetPr.
Note the type mwSize used above, and also mwIndex, are defined
as the native precision of the indexing in Octave on the platform on
which the mex-file is built. This allows both 32- and 64-bit platforms
to support mex-files. mwSize is used to define array dimensions
and the maximum number or elements, while mwIndex is used to define
indexing into arrays.
An example that demonstrates how to work with arbitrary real or complex double precision arrays is given by the file ‘mypow2.c’ shown below.
#include "mex.h"
void
mexFunction (int nlhs, mxArray* plhs[],
int nrhs, const mxArray* prhs[])
{
mwSize n;
mwIndex i;
double *vri, *vro;
if (nrhs != 1 || ! mxIsNumeric (prhs[0]))
mexErrMsgTxt ("ARG1 must be a matrix");
n = mxGetNumberOfElements (prhs[0]);
plhs[0] = mxCreateNumericArray (mxGetNumberOfDimensions (prhs[0]),
mxGetDimensions (prhs[0]),
mxGetClassID (prhs[0]),
mxIsComplex (prhs[0]));
vri = mxGetPr (prhs[0]);
vro = mxGetPr (plhs[0]);
if (mxIsComplex (prhs[0]))
{
double *vii, *vio;
vii = mxGetPi (prhs[0]);
vio = mxGetPi (plhs[0]);
for (i = 0; i < n; i++)
{
vro[i] = vri[i] * vri[i] - vii[i] * vii[i];
vio[i] = 2 * vri[i] * vii[i];
}
}
else
{
for (i = 0; i < n; i++)
vro[i] = vri[i] * vri[i];
}
}
|
with an example of its use
b = randn (4,1) + 1i * randn (4,1); all (b.^2 == mypow2 (b)) ⇒ 1 |
The example above uses the functions mxGetDimensions,
mxGetNumberOfElements, and mxGetNumberOfDimensions to work
with the dimensions of multi-dimensional arrays. The functions
mxGetM, and mxGetN are also available to find the number
of rows and columns in a 2-D matrix.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
As mex-files do not make the distinction between single and double quoted strings within Octave, there is perhaps less complexity in the use of strings and character matrices in mex-files. An example of their use that parallels the demo in ‘stringdemo.cc’ is given in the file ‘mystring.c’, as shown below.
#include <string.h>
#include "mex.h"
void
mexFunction (int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
mwSize m, n;
mwIndex i, j;
mxChar *pi, *po;
if (nrhs != 1 || ! mxIsChar (prhs[0])
|| mxGetNumberOfDimensions (prhs[0]) > 2)
mexErrMsgTxt ("ARG1 must be a char matrix");
m = mxGetM (prhs[0]);
n = mxGetN (prhs[0]);
pi = mxGetChars (prhs[0]);
plhs[0] = mxCreateNumericMatrix (m, n, mxCHAR_CLASS, mxREAL);
po = mxGetChars (plhs[0]);
for (j = 0; j < n; j++)
for (i = 0; i < m; i++)
po[j*m + m - 1 - i] = pi[j*m + i];
}
|
An example of its expected output is
mystring (["First String"; "Second String"]) ⇒ Second String First String |
Other functions in the mex interface for handling character strings are
mxCreateString, mxArrayToString, and
mxCreateCharMatrixFromStrings. In a mex-file, a character string
is considered to be a vector rather than a matrix. This is perhaps an
arbitrary distinction as the data in the mxArray for the matrix is
consecutive in any case.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
One can perform exactly the same operations on Cell arrays in mex-files as in oct-files. An example that reduplicates the function of the ‘celldemo.cc’ oct-file in a mex-file is given by ‘mycell.c’ as shown below.
#include "mex.h"
void
mexFunction (int nlhs, mxArray* plhs[],
int nrhs, const mxArray* prhs[])
{
mwSize n;
mwIndex i;
if (nrhs != 1 || ! mxIsCell (prhs[0]))
mexErrMsgTxt ("ARG1 must be a cell");
n = mxGetNumberOfElements (prhs[0]);
n = (n > nlhs ? nlhs : n);
for (i = 0; i < n; i++)
plhs[i] = mxDuplicateArray (mxGetCell (prhs[0], i));
}
|
The output is identical to the oct-file version as well.
[b1, b2, b3] = mycell ({1, [1, 2], "test"})
⇒
b1 = 1
b2 =
1 2
b3 = test
|
Note in the example the use of the mxDuplicateArray function. This
is needed as the mxArray pointer returned by mxGetCell
might be deallocated. The inverse function to mxGetCell, used for
setting Cell values, is mxSetCell and is defined as
void mxSetCell (mxArray *ptr, int idx, mxArray *val); |
Finally, to create a cell array or matrix, the appropriate functions are
mxArray *mxCreateCellArray (int ndims, const int *dims); mxArray *mxCreateCellMatrix (int m, int n); |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The basic function to create a structure in a mex-file is
mxCreateStructMatrix which creates a structure array with a two
dimensional matrix, or mxCreateStructArray.
mxArray *mxCreateStructArray (int ndims, int *dims,
int num_keys,
const char **keys);
mxArray *mxCreateStructMatrix (int rows, int cols,
int num_keys,
const char **keys);
|
Accessing the fields of the structure can then be performed with
mxGetField and mxSetField or alternatively with the
mxGetFieldByNumber and mxSetFieldByNumber functions.
mxArray *mxGetField (const mxArray *ptr, mwIndex index,
const char *key);
mxArray *mxGetFieldByNumber (const mxArray *ptr,
mwIndex index, int key_num);
void mxSetField (mxArray *ptr, mwIndex index,
const char *key, mxArray *val);
void mxSetFieldByNumber (mxArray *ptr, mwIndex index,
int key_num, mxArray *val);
|
A difference between the oct-file interface to structures and the
mex-file version is that the functions to operate on structures in
mex-files directly include an index over the elements of the
arrays of elements per field; Whereas, the oct-file structure
includes a Cell Array per field of the structure.
An example that demonstrates the use of structures in a mex-file can be found in the file ‘mystruct.c’ shown below.
#include "mex.h"
void
mexFunction (int nlhs, mxArray* plhs[],
int nrhs, const mxArray* prhs[])
{
int i;
mwIndex j;
mxArray *v;
const char *keys[] = { "this", "that" };
if (nrhs != 1 || ! mxIsStruct (prhs[0]))
mexErrMsgTxt ("expects struct");
for (i = 0; i < mxGetNumberOfFields (prhs[0]); i++)
for (j = 0; j < mxGetNumberOfElements (prhs[0]); j++)
{
mexPrintf ("field %s(%d) = ", mxGetFieldNameByNumber (prhs[0], i), j);
v = mxGetFieldByNumber (prhs[0], j, i);
mexCallMATLAB (0, NULL, 1, &v, "disp");
}
v = mxCreateStructMatrix (2, 2, 2, keys);
mxSetFieldByNumber (v, 0, 0, mxCreateString ("this1"));
mxSetFieldByNumber (v, 0, 1, mxCreateString ("that1"));
mxSetFieldByNumber (v, 1, 0, mxCreateString ("this2"));
mxSetFieldByNumber (v, 1, 1, mxCreateString ("that2"));
mxSetFieldByNumber (v, 2, 0, mxCreateString ("this3"));
mxSetFieldByNumber (v, 2, 1, mxCreateString ("that3"));
mxSetFieldByNumber (v, 3, 0, mxCreateString ("this4"));
mxSetFieldByNumber (v, 3, 1, mxCreateString ("that4"));
if (nlhs)
plhs[0] = v;
}
|
An example of the behavior of this function within Octave is then
a(1).f1 = "f11"; a(1).f2 = "f12";
a(2).f1 = "f21"; a(2).f2 = "f22";
b = mystruct (a);
⇒ field f1(0) = f11
field f1(1) = f21
field f2(0) = f12
field f2(1) = f22
b
⇒ 2x2 struct array containing the fields:
this
that
b(3)
⇒ scalar structure containing the fields:
this = this3
that = that3
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The Octave format for sparse matrices is identical to the mex format in that it is a compressed column sparse format. Also in both, sparse matrices are required to be two-dimensional. The only difference is that the real and imaginary parts of the matrix are stored separately.
The mex-file interface, in addition to using mxGetM, mxGetN,
mxSetM, mxSetN, mxGetPr, mxGetPi,
mxSetPr, and mxSetPi, also supplies the following functions.
mwIndex *mxGetIr (const mxArray *ptr); mwIndex *mxGetJc (const mxArray *ptr); mwSize mxGetNzmax (const mxArray *ptr); void mxSetIr (mxArray *ptr, mwIndex *ir); void mxSetJc (mxArray *ptr, mwIndex *jc); void mxSetNzmax (mxArray *ptr, mwSize nzmax); |
mxGetNzmax gets the maximum number of elements that can be stored
in the sparse matrix. This is not necessarily the number of non-zero
elements in the sparse matrix. mxGetJc returns an array with one
additional value than the number of columns in the sparse matrix. The
difference between consecutive values of the array returned by
mxGetJc define the number of non-zero elements in each column of
the sparse matrix. Therefore,
mwSize nz, n; mwIndex *Jc; mxArray *m; … n = mxGetN (m); Jc = mxGetJc (m); nz = Jc[n]; |
returns the actual number of non-zero elements stored in the matrix in
nz. As the arrays returned by mxGetPr and mxGetPi
only contain the non-zero values of the matrix, we also need a pointer
to the rows of the non-zero elements, and this is given by
mxGetIr. A complete example of the use of sparse matrices in
mex-files is given by the file ‘mysparse.c’ shown below.
#include "mex.h"
void
mexFunction (int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
mwSize m, n, nz;
mxArray *v;
mwIndex i;
double *pr, *pi;
double *pr2, *pi2;
mwIndex *ir, *jc;
mwIndex *ir2, *jc2;
if (nrhs != 1 || ! mxIsSparse (prhs[0]))
mexErrMsgTxt ("ARG1 must be a sparse matrix");
m = mxGetM (prhs[0]);
n = mxGetN (prhs[0]);
nz = mxGetNzmax (prhs[0]);
if (mxIsComplex (prhs[0]))
{
mexPrintf ("Matrix is %d-by-%d complex sparse matrix", m, n);
mexPrintf (" with %d elements\n", nz);
pr = mxGetPr (prhs[0]);
pi = mxGetPi (prhs[0]);
ir = mxGetIr (prhs[0]);
jc = mxGetJc (prhs[0]);
i = n;
while (jc[i] == jc[i-1] && i != 0) i--;
mexPrintf ("last non-zero element (%d, %d) = (%g, %g)\n",
ir[nz-1]+ 1, i, pr[nz-1], pi[nz-1]);
v = mxCreateSparse (m, n, nz, mxCOMPLEX);
pr2 = mxGetPr (v);
pi2 = mxGetPi (v);
ir2 = mxGetIr (v);
jc2 = mxGetJc (v);
for (i = 0; i < nz; i++)
{
pr2[i] = 2 * pr[i];
pi2[i] = 2 * pi[i];
ir2[i] = ir[i];
}
for (i = 0; i < n + 1; i++)
jc2[i] = jc[i];
if (nlhs > 0)
plhs[0] = v;
}
else if (mxIsLogical (prhs[0]))
{
mxLogical *pbr, *pbr2;
mexPrintf ("Matrix is %d-by-%d logical sparse matrix", m, n);
mexPrintf (" with %d elements\n", nz);
pbr = mxGetLogicals (prhs[0]);
ir = mxGetIr (prhs[0]);
jc = mxGetJc (prhs[0]);
i = n;
while (jc[i] == jc[i-1] && i != 0) i--;
mexPrintf ("last non-zero element (%d, %d) = %d\n",
ir[nz-1]+ 1, i, pbr[nz-1]);
v = mxCreateSparseLogicalMatrix (m, n, nz);
pbr2 = mxGetLogicals (v);
ir2 = mxGetIr (v);
jc2 = mxGetJc (v);
for (i = 0; i < nz; i++)
{
pbr2[i] = pbr[i];
ir2[i] = ir[i];
}
for (i = 0; i < n + 1; i++)
jc2[i] = jc[i];
if (nlhs > 0)
plhs[0] = v;
}
else
{
mexPrintf ("Matrix is %d-by-%d real sparse matrix", m, n);
mexPrintf (" with %d elements\n", nz);
pr = mxGetPr (prhs[0]);
ir = mxGetIr (prhs[0]);
jc = mxGetJc (prhs[0]);
i = n;
while (jc[i] == jc[i-1] && i != 0) i--;
mexPrintf ("last non-zero element (%d, %d) = %g\n",
ir[nz-1]+ 1, i, pr[nz-1]);
v = mxCreateSparse (m, n, nz, mxREAL);
pr2 = mxGetPr (v);
ir2 = mxGetIr (v);
jc2 = mxGetJc (v);
for (i = 0; i < nz; i++)
{
pr2[i] = 2 * pr[i];
ir2[i] = ir[i];
}
for (i = 0; i < n + 1; i++)
jc2[i] = jc[i];
if (nlhs > 0)
plhs[0] = v;
}
}
|
A sample usage of mysparse is
sm = sparse ([1, 0; 0, pi]); mysparse (sm) ⇒ Matrix is 2-by-2 real sparse matrix with 2 elements last non-zero element (2, 2) = 3.14159 |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
It is possible to call other Octave functions from within a mex-file
using mexCallMATLAB. An example of the use of mexCallMATLAB
can be see in the example below.
#include "mex.h"
void
mexFunction (int nlhs, mxArray* plhs[],
int nrhs, const mxArray* prhs[])
{
char *str;
mexPrintf ("Starting file myfeval.mex\n");
mexPrintf ("I have %d inputs and %d outputs\n", nrhs, nlhs);
if (nrhs < 1 || ! mxIsString (prhs[0]))
mexErrMsgTxt ("ARG1 must be a function name");
str = mxArrayToString (prhs[0]);
mexPrintf ("I'm going to call the function %s\n", str);
if (nlhs == 0)
nlhs = 1; // Octave's automatic 'ans' variable
/* Cast prhs just to get rid of 'const' qualifier and stop compile warning */
mexCallMATLAB (nlhs, plhs, nrhs-1, (mxArray**)prhs+1, str);
mxFree (str);
}
|
If this code is in the file ‘myfeval.c’, and is compiled to ‘myfeval.mex’, then an example of its use is
a = myfeval ("sin", 1)
⇒ Starting file myfeval.mex
I have 2 inputs and 1 outputs
I'm going to call the interpreter function sin
a = 0.84147
|
Note that it is not possible to use function handles or inline functions within a mex-file.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The libraries Octave itself uses can be utilized in standalone applications. These applications then have access, for example, to the array and matrix classes, as well as to all of the Octave algorithms. The following C++ program, uses class Matrix from ‘liboctave.a’ or ‘liboctave.so’.
#include <iostream>
#include <octave/oct.h>
int
main (void)
{
std::cout << "Hello Octave world!\n";
int n = 2;
Matrix a_matrix = Matrix (n, n);
for (octave_idx_type i = 0; i < n; i++)
for (octave_idx_type j = 0; j < n; j++)
a_matrix(i,j) = (i + 1) * 10 + (j + 1);
std::cout << a_matrix;
return 0;
}
|
mkoctfile can be used to build a standalone application with a command like
$ mkoctfile --link-stand-alone standalone.cc -o standalone $ ./standalone Hello Octave world! 11 12 21 22 $ |
Note that the application standalone will be dynamically linked
against the Octave libraries and any Octave support libraries. The above
allows the Octave math libraries to be used by an application. It does
not, however, allow the script files, oct-files, or built-in functions of
Octave to be used by the application. To do that the Octave interpreter
needs to be initialized first. An example of how to do this can then be
seen in the code
#include <iostream>
#include <octave/oct.h>
#include <octave/octave.h>
#include <octave/parse.h>
#include <octave/toplev.h>
int
main (void)
{
string_vector argv (2);
argv(0) = "embedded";
argv(1) = "-q";
octave_main (2, argv.c_str_vec (), 1);
octave_idx_type n = 2;
octave_value_list in;
for (octave_idx_type i = 0; i < n; i++)
in(i) = octave_value (5 * (i + 2));
octave_value_list out = feval ("gcd", in, 1);
if (! error_state && out.length () > 0)
std::cout << "GCD of ["
<< in(0).int_value ()
<< ", "
<< in(1).int_value ()
<< "] is " << out(0).int_value ()
<< std::endl;
else
std::cout << "invalid\n";
clean_up_and_exit (0);
}
|
which, as before, is compiled and run as a standalone application with
$ mkoctfile --link-stand-alone embedded.cc -o embedded $ ./embedded GCD of [10, 15] is 5 $ |
It is worth noting that, if only built-in functions are to be called from
a C++ standalone program, then it does not need to initialize the
interpreter to do so. The general rule is that, for a built-in
function named function_name in the interpreter, there will be
a C++ function named Ffunction_name (note the prepended capital
F) accessible in the C++ API. The declarations for all built-in
functions are collected in the header file builtin-defun-decls.h.
This feature should be used with care as the list of built-in functions can
change. No guarantees can be made that a function that is currently built in
won’t be implemented as a .m file or as a dynamically linked function in the
future. An example of how to call built-in functions from C++ can be seen in the
code
#include <iostream>
#include <octave/oct.h>
#include <octave/builtin-defun-decls.h>
int
main (void)
{
int n = 2;
Matrix a_matrix = Matrix (n, n);
for (octave_idx_type i = 0; i < n; i++)
for (octave_idx_type j = 0; j < n; j++)
a_matrix(i,j) = (i + 1) * 10 + (j + 1);
std::cout << "This is a matrix:" << std::endl
<< a_matrix << std::endl;
octave_value_list in;
in(0) = a_matrix;
octave_value_list out = Fnorm (in, 1);
double norm_of_the_matrix = out(0).double_value ();
std::cout << "This is the norm of the matrix:" << std::endl
<< norm_of_the_matrix << std::endl;
return 0;
}
|
which, again, is compiled and run as a standalone application with
$ mkoctfile --link-stand-alone standalonebuiltin.cc -o standalonebuiltin $ ./standalonebuiltin This is a matrix: 11 12 21 22 This is the norm of the matrix: 34.4952 $ |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave includes a number of functions to allow the integration of testing and demonstration code in the source code of the functions themselves.
| B.1 Test Functions | ||
| B.2 Demonstration Functions |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Perform tests from the first file in the loadpath matching name.
test can be called as a command or as a function. Called with
a single argument name, the tests are run interactively and stop
after the first error is encountered.
With a second argument the tests which are performed and the amount of output is selected.
"quiet"Don’t report all the tests as they happen, just the errors.
"normal"Report all tests as they happen, but don’t do tests which require user interaction.
"verbose"Do tests which require user interaction.
The argument fid can be used to allow batch processing. Errors
can be written to the already open file defined by fid, and
hopefully when Octave crashes this file will tell you what was happening
when it did. You can use stdout if you want to see the results as
they happen. You can also give a file name rather than an fid, in
which case the contents of the file will be replaced with the log from
the current test.
Called with a single output argument success, test returns
true if all of the tests were successful. Called with two output arguments
n and max, the number of successful tests and the total number
of tests in the file name are returned.
If the second argument is the string "grabdemo", the contents of
the demo blocks are extracted but not executed. Code for all code blocks
is concatenated and returned as code with idx being a vector
of positions of the ends of the demo blocks.
If the second argument is "explain", then name is ignored
and an explanation of the line markers used is written to the file
fid.
test scans the named script file looking for lines which start
with the identifier ‘%!’. The prefix is stripped off and the rest
of the line is processed through the Octave interpreter. If the code
generates an error, then the test is said to fail.
Since eval() will stop at the first error it encounters, you must
divide your tests up into blocks, with anything in a separate
block evaluated separately. Blocks are introduced by valid keywords like
test, function, or assert immediately following ‘%!’.
A block is defined by indentation as in Python. Lines beginning with
‘%!<whitespace>’ are part of the preceeding block.
For example:
%!test error ("this test fails!");
%!test "test doesn't fail. it doesn't generate an error";
|
When a test fails, you will see something like:
***** test error ("this test fails!")
!!!!! test failed
this test fails!
|
Generally, to test if something works, you want to assert that it produces a correct value. A real test might look something like
%!test
%! a = [1, 2, 3; 4, 5, 6]; B = [1; 2];
%! expect = [ a ; 2*a ];
%! get = kron (b, a);
%! if (any (size (expect) != size (get)))
%! error ("wrong size: expected %d,%d but got %d,%d",
%! size (expect), size (get));
%! elseif (any (any (expect != get)))
%! error ("didn't get what was expected.");
%! endif
|
To make the process easier, use the assert function. For example,
with assert the previous test is reduced to:
%!test %! a = [1, 2, 3; 4, 5, 6]; b = [1; 2]; %! assert (kron (b, a), [ a; 2*a ]); |
assert can accept a tolerance so that you can compare results
absolutely or relatively. For example, the following all succeed:
%!test assert (1+eps, 1, 2*eps) # absolute error %!test assert (100+100*eps, 100, -2*eps) # relative error |
You can also do the comparison yourself, but still have assert generate the error:
%!test assert (isempty ([])) %!test assert ([1, 2; 3, 4] > 0) |
Because assert is so frequently used alone in a test block, there
is a shorthand form:
%!assert (…) |
which is equivalent to:
%!test assert (…) |
Occasionally a block of tests will depend on having optional
functionality in Octave. Before testing such blocks the availability of
the required functionality must be checked. A %!testif HAVE_XXX
block will only be run if Octave was compiled with functionality
‘HAVE_XXX’. For example, the sparse single value decomposition,
svds(), depends on having the ARPACK library. All of the tests
for svds begin with
%!testif HAVE_ARPACK |
Review ‘config.h’ or octave_config_info ("features") to see some
of the possible values to check.
Sometimes during development there is a test that should work but is
known to fail. You still want to leave the test in because when the
final code is ready the test should pass, but you may not be able to
fix it immediately. To avoid unnecessary bug reports for these known
failures, mark the block with xtest rather than test:
%!xtest assert (1==0)
%!xtest fail ("success=1", "error")
|
In this case, the test will run and any failure will be reported.
However, testing is not aborted and subsequent test blocks will be
processed normally. Another use of xtest is for statistical
tests which should pass most of the time but are known to fail
occasionally.
Each block is evaluated in its own function environment, which means
that variables defined in one block are not automatically shared
with other blocks. If you do want to share variables, then you
must declare them as shared before you use them. For example, the
following declares the variable a, gives it an initial value (default
is empty), and then uses it in several subsequent tests.
%!shared a %! a = [1, 2, 3; 4, 5, 6]; %!assert (kron ([1; 2], a), [ a; 2*a ]); %!assert (kron ([1, 2], a), [ a, 2*a ]); %!assert (kron ([1,2; 3,4], a), [ a,2*a; 3*a,4*a ]); |
You can share several variables at the same time:
%!shared a, b |
You can also share test functions:
%!function a = fn (b) %! a = 2*b; %!endfunction %!assert (fn(2), 4); |
Note that all previous variables and values are lost when a new shared block is declared.
Remember that %!function begins a new block and that
%!endfunction ends this block. Be aware that until a new block
is started, lines starting with ‘%!<space>’ will be discarded as comments.
The following is nearly identical to the example above, but does nothing.
%!function a = fn (b) %! a = 2*b; %!endfunction %! assert (fn(2), 4); |
Because there is a space after ‘%!’ the assert statement does
not begin a new block and this line is treated as a comment.
Error and warning blocks are like test blocks, but they only succeed
if the code generates an error. You can check the text of the error
is correct using an optional regular expression <pattern>.
For example:
%!error <passes!> error ("this test passes!");
|
If the code doesn’t generate an error, the test fails. For example:
%!error "this is an error because it succeeds."; |
produces
***** error "this is an error because it succeeds."; !!!!! test failed: no error |
It is important to automate the tests as much as possible, however
some tests require user interaction. These can be isolated into
demo blocks, which if you are in batch mode, are only run when
called with demo or the verbose option to test.
The code is displayed before it is executed. For example,
%!demo %! t = [0:0.01:2*pi]; x = sin (t); %! plot (t, x); %! # you should now see a sine wave in your figure window |
produces
funcname example 1: t = [0:0.01:2*pi]; x = sin (t); plot (t, x); # you should now see a sine wave in your figure window Press <enter> to continue: |
Note that demo blocks cannot use any shared variables. This is so that they can be executed by themselves, ignoring all other tests.
If you want to temporarily disable a test block, put # in place
of the block type. This creates a comment block which is echoed
in the log file but not executed. For example:
%!#demo %! t = [0:0.01:2*pi]; x = sin (t); %! plot (t, x); %! # you should now see a sine wave in your figure window |
The following trivial code snippet provides examples for the use of fail, assert, error and xtest:
function output = must_be_zero (input)
if (input != 0)
error ("Non-zero input!")
endif
output = input;
endfunction
%!fail ("must_be_zero (1)");
%!assert (must_be_zero (0), 0);
%!error <Non-zero> must_be_zero (1);
%!xtest error ("This code generates an error");
|
When putting this a file ‘must_be_zero.m’, and running the test, we see
test must_be_zero verbose
⇒
>>>>> /path/to/must_be_zero.m
***** fail ("must_be_zero (1)");
***** assert (must_be_zero (0), 0);
***** error <Non-zero> must_be_zero (1);
***** xtest error ("This code generates an error");
!!!!! known failure
This code generates an error
PASSES 4 out of 4 tests (1 expected failures)
|
%!testcheck that entire block is correct
%!testif HAVE_XXXcheck block only if Octave was compiled with feature HAVE_XXX.
%!xtestcheck block, report a test failure but do not abort testing.
%!errorcheck for correct error message
%!warningcheck for correct warning message
%!demodemo only executes in interactive mode
%!#comment: ignore everything within the block
%!shared x,y,zdeclare variables for use in multiple tests
%!functiondefine a function for use in multiple tests
%!endfunctionclose a function definition
%!assert (x, y, tol)shorthand for %!test assert (x, y, tol)
You can also create test scripts for built-in functions and your own C++
functions. To do so, put a file with the bare function name (no .m
extension) in a directory in the load path and it will be discovered by
the test function. Alternatively, you can embed tests directly in your
C++ code:
/*
%!test disp ("this is a test")
*/
|
or
#if 0
%!test disp ("this is a test")
#endif
|
However, in this case the raw source code will need to be on the load
path and the user will have to remember to type
test ("funcname.cc").
Produce an error if the specified condition is not met. assert can
be called in three different ways.
assert (cond)assert (cond, errmsg, …)assert (cond, msg_id, errmsg, …)Called with a single argument cond, assert produces an
error if cond is zero. When called with more than one argument the
additional arguments are passed to the error function.
assert (observed, expected)Produce an error if observed is not the same as expected. Note that observed and expected can be scalars, vectors, matrices, strings, cell arrays, or structures.
assert (observed, expected, tol)Produce an error if observed is not the same as expected but equality
comparison for numeric data uses a tolerance tol.
If tol is positive then it is an absolute tolerance which will produce
an error if abs (observed - expected) > abs (tol).
If tol is negative then it is a relative tolerance which will produce
an error if abs (observed - expected) >
abs (tol * expected). If expected is zero tol will
always be interpreted as an absolute tolerance. If tol is not scalar
its dimensions must agree with those of observed and expected
and tests are performed on an element-wise basis.
Return true if code fails with an error message matching pattern, otherwise produce an error. Note that code is a string and if code runs successfully, the error produced is:
expected error <.> but got none |
Code must be in the form of a string that may be passed by
fail to the Octave interpreter via the evalin function,
that is, a (quoted) string constant or a string variable.
If called with two arguments, the behavior is similar to
fail (code), except the return value will only be true if
code fails with an error message containing pattern (case sensitive).
If the code fails with a different error to that given in pattern,
the message produced is:
expected <pattern>
but got <text of actual error>
|
The angle brackets are not part of the output.
Called with three arguments, the behavior is similar to
fail (code, pattern), but produces an error if no
warning is given during code execution or if the code fails.
See also: assert.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Run example code block n associated with the function name. If n is not specified, all examples are run.
Examples are stored in the script file, or in a file with the same
name but no extension located on Octave’s load path. To keep examples
separate from regular script code, all lines are prefixed by %!. Each
example must also be introduced by the keyword "demo" flush left
to the prefix with no intervening spaces. The remainder of the example
can contain arbitrary Octave code. For example:
%!demo %! t = 0:0.01:2*pi; %! x = sin (t); %! plot (t, x); %! %------------------------------------------------- %! % the figure window shows one cycle of a sine wave |
Note that the code is displayed before it is executed, so a simple
comment at the end suffices for labeling what is being shown. It is
generally not necessary to use disp or printf within the demo.
Demos are run in a function environment with no access to external variables. This means that every demo must have separate initialization code. Alternatively, all demos can be combined into a single large demo with the code
%! input("Press <enter> to continue: ","s");
|
between the sections, but this is discouraged. Other techniques
to avoid multiple initialization blocks include using multiple plots
with a new figure command between each plot, or using subplot
to put multiple plots in the same window.
Also, because demo evaluates within a function context, you cannot
define new functions inside a demo. If you must have function blocks,
rather than just anonymous functions or inline functions, you will have to
use eval (example ("function",n)) to see them. Because eval only
evaluates one line, or one statement if the statement crosses
multiple lines, you must wrap your demo in "if 1 <demo stuff> endif"
with the "if" on the same line as "demo". For example:
%!demo if 1 %! function y=f(x) %! y=x; %! endfunction %! f(3) %! endif |
Display the code for example n associated with the function name, but do not run it. If n is not specified, all examples are displayed.
When called with output arguments, the examples are returned in the form of a string s, with idx indicating the ending position of the various examples.
See demo for a complete explanation.
Execute built-in demos for all function files in the specified directory. Also executes demos in any C++ source files found in the directory, for use with dynamically linked functions.
If no directory is specified, operate on all directories in Octave’s search path for functions.
Execute built-in tests for all function files in the specified directory. Also executes tests in any C++ source files found in the directory, for use with dynamically linked functions.
If no directory is specified, operate on all directories in Octave’s search path for functions.
Determine the execution time of an expression (f) for various input values (n). The n are log-spaced from 1 to max_n. For each n, an initialization expression (init) is computed to create any data needed for the test. If a second expression (f2) is given then the execution times of the two expressions are compared. When called without output arguments the results are printed to stdout and displayed graphically.
fThe code expression to evaluate.
max_nThe maximum test length to run. The default value is 100. Alternatively,
use [min_n, max_n] or specify the n exactly with
[n1, n2, …, nk].
initInitialization expression for function argument values. Use k
for the test number and n for the size of the test. This should
compute values for all variables used by f. Note that init will
be evaluated first for k = 0, so things which are constant throughout
the test series can be computed once. The default value is
x = randn (n, 1).
f2An alternative expression to evaluate, so that the speed of two
expressions can be directly compared. The default is [].
tolTolerance used to compare the results of expression f and expression
f2. If tol is positive, the tolerance is an absolute one.
If tol is negative, the tolerance is a relative one. The default is
eps. If tol is Inf, then no comparison will be made.
orderThe time complexity of the expression O(a*n^p). This
is a structure with fields a and p.
nThe values n for which the expression was calculated AND the execution time was greater than zero.
T_fThe nonzero execution times recorded for the expression f in seconds.
T_f2The nonzero execution times recorded for the expression f2 in seconds.
If required, the mean time ratio is simply mean (T_f ./ T_f2).
The slope of the execution time graph shows the approximate power of the asymptotic running time O(n^p). This power is plotted for the region over which it is approximated (the latter half of the graph). The estimated power is not very accurate, but should be sufficient to determine the general order of an algorithm. It should indicate if, for example, the implementation is unexpectedly O(n^2) rather than O(n) because it extends a vector each time through the loop rather than pre-allocating storage. In the current version of Octave, the following is not the expected O(n).
speed ("for i = 1:n, y{i} = x(i); endfor", "", [1000, 10000])
|
But it is if you preallocate the cell array y:
speed ("for i = 1:n, y{i} = x(i); endfor", ...
"x = rand (n, 1); y = cell (size (x));", [1000, 10000])
|
An attempt is made to approximate the cost of individual
operations, but it is wildly inaccurate. You can improve the
stability somewhat by doing more work for each n. For
example:
speed ("airy(x)", "x = rand (n, 10)", [10000, 100000])
|
When comparing two different expressions (f, f2), the slope of the line on the speedup ratio graph should be larger than 1 if the new expression is faster. Better algorithms have a shallow slope. Generally, vectorizing an algorithm will not change the slope of the execution time graph, but will shift it relative to the original. For example:
speed ("sum (x)", "", [10000, 100000], ...
"v = 0; for i = 1:length (x), v += x(i); endfor")
|
The following is a more complex example. If there was an original version
of xcorr using for loops and a second version using an FFT, then
one could compare the run speed for various lags as follows, or for a fixed
lag with varying vector lengths as follows:
speed ("xcorr (x, n)", "x = rand (128, 1);", 100,
"xcorr_orig (x, n)", -100*eps)
speed ("xcorr (x, 15)", "x = rand (20+n, 1);", 100,
"xcorr_orig (x, n)", -100*eps)
|
Assuming one of the two versions is in xcorr_orig, this
would compare their speed and their output values. Note that the
FFT version is not exact, so one must specify an acceptable tolerance on
the comparison 100*eps. In this case, the comparison should be
computed relatively, as abs ((x - y) ./ y) rather
than absolutely as abs (x - y).
Type example ("speed") to see some real examples or demo ("speed") to run them.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This chapter describes no additional features of Octave. Instead it gives advice on making effective use of the features described in the previous chapters.
| C.1 Writing Clean Octave Programs | Writing clean and robust programs. | |
| C.2 Tips on Writing Comments | Conventions for writing comments. | |
| C.3 Conventional Headers for Octave Functions | Standard headers for functions. | |
| C.4 Tips for Documentation Strings | Writing readable documentation strings. |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Here are some tips for avoiding common errors in writing Octave code intended for widespread use:
If you write a function that you think ought to be added to Octave under
a certain name, such as fiddle_matrix, don’t call it by that name
in your program. Call it mylib_fiddle_matrix in your program,
and send mail to maintainers@octave.org suggesting that it
be added to Octave. If and when it is, the name can be changed easily
enough.
If one prefix is insufficient, your package may use two or three alternative common prefixes, so long as they make sense.
Separate the prefix from the rest of the symbol name with an underscore ‘_’. This will be consistent with Octave itself and with most Octave programs.
error
(or usage). The error and usage functions do not
return.
See section How Octave Reports Errors.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Here are the conventions to follow when writing comments.
Comments that start with a single sharp-sign, ‘#’, should all be
aligned to the same column on the right of the source code. Such
comments usually explain how the code on the same line does its job. In
the Emacs mode for Octave, the M-; (indent-for-comment)
command automatically inserts such a ‘#’ in the right place, or
aligns such a comment if it is already present.
Comments that start with a double sharp-sign, ‘##’, should be aligned to the same level of indentation as the code. Such comments usually describe the purpose of the following lines or the state of the program at that point.
The indentation commands of the Octave mode in Emacs, such as M-;
(indent-for-comment) and TAB (octave-indent-line)
automatically indent comments according to these conventions,
depending on the number of semicolons. See (emacs)Comments section ‘Manipulating Comments’ in The GNU Emacs Manual.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave has conventions for using special comments in function files to give information such as who wrote them. This section explains these conventions.
The top of the file should contain a copyright notice, followed by a block of comments that can be used as the help text for the function. Here is an example:
## Copyright (C) 1996, 1997, 2007 John W. Eaton
##
## This file is part of Octave.
##
## Octave is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public
## License as published by the Free Software Foundation;
## either version 3 of the License, or (at your option) any
## later version.
##
## Octave is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied
## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public
## License along with Octave; see the file COPYING. If not,
## see <http://www.gnu.org/licenses/>.
## usage: [IN, OUT, PID] = popen2 (COMMAND, ARGS)
##
## Start a subprocess with two-way communication. COMMAND
## specifies the name of the command to start. ARGS is an
## array of strings containing options for COMMAND. IN and
## OUT are the file ids of the input and streams for the
## subprocess, and PID is the process id of the subprocess,
## or -1 if COMMAND could not be executed.
##
## Example:
##
## [in, out, pid] = popen2 ("sort", "-nr");
## fputs (in, "these\nare\nsome\nstrings\n");
## fclose (in);
## while (ischar (s = fgets (out)))
## fputs (stdout, s);
## endwhile
## fclose (out);
|
Octave uses the first block of comments in a function file that do not appear to be a copyright notice as the help text for the file. For Octave to recognize the first comment block as a copyright notice, it must start with the word ‘Copyright’ after stripping the leading comment characters.
After the copyright notice and help text come several header comment lines, each beginning with ‘## header-name:’. For example,
## Author: jwe ## Keywords: subprocesses input-output ## Maintainer: jwe |
Here is a table of the conventional possibilities for header-name:
This line states the name and net address of at least the principal author of the library.
## Author: John W. Eaton <jwe@octave.org> |
This line should contain a single name/address as in the Author line, or an address only, or the string ‘jwe’. If there is no maintainer line, the person(s) in the Author field are presumed to be the maintainers. The example above is mildly bogus because the maintainer line is redundant.
The idea behind the ‘Author’ and ‘Maintainer’ lines is to make possible a function to “send mail to the maintainer” without having to mine the name out by hand.
Be sure to surround the network address with ‘<…>’ if you include the person’s full name as well as the network address.
This optional line gives the original creation date of the file. For historical interest only.
If you wish to record version numbers for the individual Octave program, put them in this line.
In this header line, place the name of the person who adapted the library for installation (to make it fit the style conventions, for example).
This line lists keywords. Eventually, it will be used by an apropos command to allow people will find your package when they’re looking for things by topic area. To separate the keywords, you can use spaces, commas, or both.
Just about every Octave function ought to have the ‘Author’ and ‘Keywords’ header comment lines. Use the others if they are appropriate. You can also put in header lines with other header names—they have no standard meanings, so they can’t do any harm.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
As noted above, documentation is typically in a commented header block on an Octave function following the copyright statement. The help string shown above is an unformatted string and will be displayed as is by Octave. Here are some tips for the writing of documentation strings.
The documentation string can have additional lines that expand on the details of how to use the function or variable. The additional lines should also be made up of complete sentences.
However, rather than simply filling the entire documentation string, you can make it much more readable by choosing line breaks with care. Use blank lines between topics if the documentation string is long.
x,y,z,t,w
A,B,M
str,s
fname
c,cstr
/ refers to its second argument as ‘DIVISOR’, because the
actual argument name is divisor.
Also use all caps for meta-syntactic variables, such as when you show the decomposition of a list or vector into subunits, some of which may vary.
Octave also allows extensive formatting of the help string of functions using Texinfo. The effect on the online documentation is relatively small, but makes the help string of functions conform to the help of Octave’s own functions. However, the effect on the appearance of printed or online documentation will be greatly improved.
The fundamental building block of Texinfo documentation strings is the
Texinfo-macro @deftypefn, which takes three arguments: The class
the function is in, its output arguments, and the function’s
signature. Typical classes for functions include Function File
for standard Octave functions, and Loadable Function for
dynamically linked functions. A skeletal Texinfo documentation string
therefore looks like this
-*- texinfo -*-
@deftypefn {Function File} {@var{ret} =} fn (…)
@cindex index term
Help text in Texinfo format. Code samples should be marked
like @code{sample of code} and variables should be marked
as @var{variable}.
@seealso{fn2, fn3}
@end deftypefn
|
This help string must be commented in user functions, or in the help
string of the DEFUN_DLD macro for dynamically loadable
functions. The important aspects of the documentation string are
This string signals Octave that the following text is in Texinfo format, and should be the first part of any help string in Texinfo format.
The entire help string should be enclosed within the block defined by deftypefn.
This generates an index entry, and can be useful when the function is included as part of a larger piece of documentation. It is ignored within Octave’s help viewer. Only one index term may appear per line but multiple @cindex lines are valid if the function should be filed under different terms.
All variables should be marked with this macro. The markup of variables is then changed appropriately for display.
All samples of code should be marked with this macro for the same reasons as the @var macro.
All samples of code which are quoted should use this more specialized macro. This happens frequently when discussing graphics properties such as "position" or options such as "on"/"off".
This is a comma separated list of function names that allows cross referencing from one function documentation string to another.
Texinfo format has been designed to generate output for online viewing with text terminals as well as generating high-quality printed output. To these ends, Texinfo has commands which control the diversion of parts of the document into a particular output processor. Three formats are of importance: info, HTML, and TeX. These are selected with
@ifinfo Text area for info only @end ifinfo |
@ifhtml Text area for HTML only @end ifhtml |
@tex Text area for TeX only @end tex |
Note that often TeX output can be used in HTML documents and so often
the @ifhtml blocks are unnecessary. If no specific output
processor is chosen, by default, the text goes into all output
processors. It is usual to have the above blocks in pairs to allow the
same information to be conveyed in all output formats, but with a
different markup. Currently, most Octave documentation only makes a
distinction between TeX and all other formats. Therefore, the
following construct is seen repeatedly.
@tex text for TeX only @end tex @ifnottex text for info, HTML, plaintext @end ifnottex |
Another important feature of Texinfo that is often used in Octave help
strings is the @example environment. An example of its use is
@example
@group
@code{2 * 2}
@result{} 4
@end group
@end example
|
which produces
|
The @group block prevents the example from being split across a
page boundary, while the @result{} macro produces a right
arrow signifying the result of a command. If your example is larger than
20 lines it is better NOT to use grouping so that a reasonable page
boundary can be calculated.
In many cases a function has multiple ways in which it can be called,
and the @deftypefnx macro can be used to give alternatives. For
example
-*- texinfo -*-
@deftypefn {Function File} {@var{a} =} fn (@var{x}, …)
@deftypefnx {Function File} {@var{a} =} fn (@var{y}, …)
Help text in Texinfo format.
@end deftypefn
|
Many complete examples of Texinfo documentation can be taken from the
help strings for the Octave functions themselves. A relatively complete
example of which is the nchoosek function. The Texinfo
documentation string for nchoosek is
-*- texinfo -*-
@deftypefn {Function File} {@var{c} =} nchoosek (@var{n}, @var{k})
@deftypefnx {Function File} {@var{c} =} nchoosek (@var{set}, @var{k})
Compute the binomial coefficient or all combinations of a set of items.
If @var{n} is a scalar then calculate the binomial coefficient
of @var{n} and @var{k} which is defined as
@tex
$$
{n \choose k} = {n (n-1) (n-2) \cdots (n-k+1) \over k!}
= {n! \over k! (n-k)!}
$$
@end tex
@ifnottex
@example
@group
/ \
| n | n (n-1) (n-2) @dots{} (n-k+1) n!
| | = ------------------------- = ---------
| k | k! k! (n-k)!
\ /
@end group
@end example
@end ifnottex
@noindent
This is the number of combinations of @var{n} items taken in groups of
size @var{k}.
If the first argument is a vector, @var{set}, then generate all
combinations of the elements of @var{set}, taken @var{k} at a time, with
one row per combination. The result @var{c} has @var{k} columns and
@w{@code{nchoosek (length (@var{set}), @var{k})}} rows.
For example:
How many ways can three items be grouped into pairs?
@example
@group
nchoosek (3, 2)
@result{} 3
@end group
@end example
What are the possible pairs?
@example
@group
nchoosek (1:3, 2)
@result{} 1 2
1 3
2 3
@end group
@end example
@code{nchoosek} works only for non-negative, integer arguments. Use
@code{bincoeff} for non-integer and negative scalar arguments, or for
computing many binomial coefficients at once with vector inputs
for @var{n} or @var{k}.
@seealso{bincoeff, perms}
@end deftypefn
|
which demonstrates most of the concepts discussed above.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This chapter is dedicated to those who wish to contribute code to Octave.
| D.1 How to Contribute | ||
| D.2 Building the Development Sources | ||
| D.3 Basics of Generating a Changeset | ||
| D.4 General Guidelines | ||
| D.5 Octave Sources (m-files) | ||
| D.6 C++ Sources | ||
| D.7 Other Sources |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The mailing list for Octave development discussions is maintainers@octave.org. Patches should be submitted to Octave’s patch tracker. This concerns the development of Octave core, i.e., code that goes in to Octave directly. You may consider developing and publishing a package instead; a great place for this is the allied Octave-Forge project (http://octave.sourceforge.net). Note that the Octave core project is inherently more conservative and follows narrower rules.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The directions for building from the development sources change from time to time, so you should read the resources for developers on the web or in the development sources archive. Start here: http://www.octave.org/get-involved.html.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The best way to contribute is to create a Mercurial changeset and submit it to the bug or patch trackers(13). Mercurial is the source code management system currently used to develop Octave. Other forms of contributions (e.g., simple diff patches) are also acceptable, but they slow down the review process. If you want to make more contributions, you should really get familiar with Mercurial. A good place to start is http://www.selenic.com/mercurial/wiki/index.cgi/Tutorial. There you will also find help about how to install Mercurial.
A simple contribution sequence could look like this:
hg clone http://www.octave.org/hg/octave
# make a local copy of the octave
# source repository
cd octave
# change some sources…
hg commit -m "make Octave the coolest software ever"
# commit the changeset into your
# local repository
hg export -o ../cool.diff tip
# export the changeset to a diff
# file
# attach ../cool.diff to your bug report
|
You may want to get familiar with Mercurial queues to manage your changesets. To work with queues you must activate the extension mq with the following entry in Mercurial’s configuration file ‘.hgrc’ (or ‘Mercurial.ini’ on Windows):
[extensions] mq= |
Here is a slightly more complex example using Mercurial queues, where work on two unrelated changesets is done in parallel and one of the changesets is updated after discussion on the bug tracker:
hg qnew nasty_bug # create a new patch
# change sources…
hg qref # save the changes into the patch
# change even more…
hg qref -m "solution to nasty bug!"
# save again with commit message
hg export -o ../nasty.diff tip
# export the patch
# attach ../nasty.diff to your bug report
hg qpop # undo the application of the patch
# and remove the changes from the
# source tree
hg qnew doc_improvements # create an unrelated patch
# change doc sources…
hg qref -m "could not find myfav.m in the doc"
# save the changes into the patch
hg export -o ../doc.diff tip
# export the second patch
# attach ../doc.diff to your bug report
hg qpop
# discussion in the bug tracker …
hg qpush nasty_bug # apply the patch again
# change sources yet again …
hg qref
hg export -o ../nasty2.diff tip
# attach ../nasty2.diff to your bug report
|
Mercurial has a few more useful extensions that really should be enabled. They are not enabled by default due to a number of factors (mostly because they don’t work in all terminal types).
The following entries in the ‘.hgrc’ are recommended
[extensions] graphlog= color= progress= pager= |
For the color extension, default color and formatting
of hg status can be modified by
[color] status.modified = magenta bold status.added = green bold status.removed = red bold status.deleted = cyan bold status.unknown = black bold status.ignored = black bold |
Sometimes a few further improvements for the pager extension are necessary. The following options should not be enabled unless paging is not working correctly.
[pager]
# Some options for the less pager, see less(1) for their meaning.
pager = LESS='FSRX' less
# Some commands that aren't paged by default; also enable paging
# for them
attend = tags, help, annotate, cat, diff, export, status, \
outgoing, incoming
|
Enabling the described extensions should immediately lead to a difference
when using the command line version of hg. Of these options, the
only one that enables a new command is graphlog. It is recommanded
that to use the command hg glog, instead of hg log, for a better
feel about what commits are being based on.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
All Octave’s sources are distributed under the GNU General Public License (GPL). Currently, Octave uses GPL version 3. For details about this license, see http://www.gnu.org/licenses/gpl.html. Therefore, whenever you create a new source file, it should have the following comment header (use appropriate year, name and comment marks):
## Copyright (C) 1996-2013 John W. Eaton <jwe@octave.org> ## ## This file is part of Octave. ## ## Octave is free software; you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 3 of the License, or ## (at your option) any later version. ## ## Octave is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Octave; see the file COPYING. If not, ## see <http://www.gnu.org/licenses/>. |
Always include commit messages in changesets. After making your source changes, record and briefly describe the changes in your commit message. You should have previously configured your ‘.hgrc’ (or ‘Mercurial.ini’ on Windows) with your name and email, which will be automatically added to your commit message. Your commit message should have a brief one-line explanation of what the commit does. If you are patching a bug, this one-line explanation should mention the bug number at the end. If your change is small and only touches one file then this is typically sufficient. If you are modifying several files, or several parts of one file, you should enumerate your changes roughly following the GNU coding standards for changelogs, as in the following example:
look for methods before constructors * symtab.cc (symbol_table::fcn_info::fcn_info_rep::find): Look for class methods before constructors, contrary to MATLAB documentation. * test/ctor-vs-method: New directory of test classes. * test/test_ctor_vs_method.m: New file. * test/Makefile.am: Include ctor-vs-method/module.mk. (FCN_FILES): Include test_ctor_vs_method.m in the list. |
In this example, the names of the file changed is listed first, and in parentheses the name of the function in that file that was modified. There is no need to mention the function for m-files that only contain one function. The commit message should describe what was changed, not why it was changed. Any explanation for why a change is needed should appear as comments in the code, particularly if there is something that might not be obvious to someone reading it later.
When submitting code which addresses a known bug on the Octave bug tracker (http://bugs.octave.org), please add ’(bug #XXXXX)’ to the first line of the commit messages. For example:
Fix bug for complex input for gradient (bug #34292). |
The preferred comment mark for places that may need further attention is
FIXME:.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Don’t use tabs. Tabs cause trouble. If you are used to them, set up your editor so that it converts tabs to spaces. Indent the bodies of statement blocks. The recommended indent is 2 spaces. When calling functions, put spaces after commas and before the calling parentheses, like this:
x = max (sin (y+3), 2); |
An exception are matrix or cell constructors:
[sin(x), cos(x)]
{sin(x), cos(x)}
|
Here, putting spaces after sin, cos would result in a
parse error. For an indexing expression, do not put a space after the
identifier (this differentiates indexing and function calls nicely).
The space after a comma is not necessary if index expressions are simple,
i.e., you may write
A(:,i,j) |
but
A([1:i-1;i+1:n], XI(:,2:n-1)) |
Use lowercase names if possible. Uppercase is acceptable for variable names consisting of 1-2 letters. Do not use mixed case names. Function names must be lowercase. Function names are global, so choose them wisely.
Always use a specific end-of-block statement (like endif,
endswitch) rather than the generic end.
Enclose the if, while, until, and switch
conditions in parentheses, as in C:
if (isvector (a)) s = sum (a); endif |
Do not do this, however, with the iteration counter portion of a
for statement. Write:
for i = 1:n b(i) = sum (a(:,i)); endfor |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Don’t use tabs. Tabs cause trouble. If you are used to them, set up your editor so that it converts tabs to spaces. Format function headers like this:
static bool
matches_patterns (const string_vector& patterns, int pat_idx,
int num_pat, const std::string& name)
|
The function name should start in column 1, and multi-line argument lists should be aligned on the first char after the open parenthesis. You should put a space before the left open parenthesis and after commas, for both function definitions and function calls.
The recommended indent is 2 spaces. When indenting, indent the statement
after control structures (like if, while, etc.). If there
is a compound statement, indent both the curly braces and the
body of the statement (so that the body gets indented by two
indents). Example:
if (have_args)
{
idx.push_back (first_args);
have_args = false;
}
else
idx.push_back (make_value_list (*p_args, *p_arg_nm, &tmp));
|
If you have nested if statements, use extra braces for extra
clarification.
Split long expressions in such a way that a continuation line starts with an operator rather than identifier. If the split occurs inside braces, continuation should be aligned with the first char after the innermost braces enclosing the split. Example:
SVD::type type = ((nargout == 0 || nargout == 1)
? SVD::sigma_only
: (nargin == 2) ? SVD::economy : SVD::std);
|
Consider putting extra braces around a multi-line expression to make it more readable, even if they are not necessary. Also, do not hesitate to put extra braces anywhere if it improves clarity.
Declare variables just before they are needed. Use local variables of blocks—it helps optimization. Don’t write a multi-line variable declaration with a single type specification and multiple variables. If the variables don’t fit on single line, repeat the type specification. Example:
octave_value retval; octave_idx_type nr = b.rows (); octave_idx_type nc = b.cols (); double d1, d2; |
Use lowercase names if possible. Uppercase is acceptable for variable names consisting of 1-2 letters. Do not use mixed case names.
Use Octave’s types and classes if possible. Otherwise, use the C++
standard library. Use of STL containers and algorithms is encouraged.
Use templates wisely to reduce code duplication. Avoid comma
expressions, labels and gotos, and explicit typecasts. If you need to
typecast, use the modern C++ casting operators. In functions, minimize
the number of return statements—use nested if statements
if possible.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Apart from C++ and Octave language (m-files), Octave’s sources include files written in C, Fortran, M4, Perl, Unix shell, AWK, Texinfo, and TeX. There are not many rules to follow when using these other languages; some of them are summarized below. In any case, the golden rule is: if you modify a source file, try to follow any conventions you can detect in the file or other similar files.
For C you should obviously follow all C++ rules that can apply.
If you modify a Fortran file, you should stay within Fortran 77 with
common extensions like END DO. Currently, we want all sources to
be compilable with the f2c and g77 compilers, without special flags if
possible. This usually means that non-legacy compilers also accept the
sources.
The M4 macro language is mainly used for Autoconf configuration files. You should follow normal M4 rules when contributing to these files. Some M4 files come from external source, namely the Autoconf archive http://autoconf-archive.cryp.to.
If you give a code example in the documentation written in Texinfo with
the @example environment, you should be aware that the text
within such an environment will not be wrapped. It is recommended that
you keep the lines short enough to fit on pages in the generated pdf or
ps documents. Here is a ruler (in an @example environment) for
finding the appropriate line width:
1 2 3 4 5 6 123456789012345678901234567890123456789012345678901234567890 |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
After being marked as deprecated for two major releases, the following functions have been removed from Octave. The third column of the table shows the version of Octave in which the function was removed. Prior to removal, each function in the list was marked as deprecated for at least two major releases. All deprecated functions issue warnings explaining that they will be removed in a future version of Octave, and which function should be used instead.
Replacement functions do not always accept precisely the same arguments as the obsolete function, but should provide equivalent functionality.
| Obsolete Function | Replacement | Version |
|---|---|---|
beta_cdf | betacdf | 3.4.0 |
beta_inv | betainv | 3.4.0 |
beta_pdf | betapdf | 3.4.0 |
beta_rnd | betarnd | 3.4.0 |
binomial_cdf | binocdf | 3.4.0 |
binomial_inv | binoinv | 3.4.0 |
binomial_pdf | binopdf | 3.4.0 |
binomial_rnd | binornd | 3.4.0 |
chisquare_cdf | chi2cdf | 3.4.0 |
chisquare_inv | chi2inv | 3.4.0 |
chisquare_pdf | chi2pdf | 3.4.0 |
chisquare_rnd | chi2rnd | 3.4.0 |
clearplot | clf | 3.4.0 |
com2str | num2str | 3.4.0 |
exponential_cdf | expcdf | 3.4.0 |
exponential_inv | expinv | 3.4.0 |
exponential_pdf | exppdf | 3.4.0 |
exponential_rnd | exprnd | 3.4.0 |
f_cdf | fcdf | 3.4.0 |
f_inv | finv | 3.4.0 |
f_pdf | fpdf | 3.4.0 |
f_rnd | frnd | 3.4.0 |
gamma_cdf | gamcdf | 3.4.0 |
gamma_inv | gaminv | 3.4.0 |
gamma_pdf | gampdf | 3.4.0 |
gamma_rnd | gamrnd | 3.4.0 |
geometric_cdf | geocdf | 3.4.0 |
geometric_inv | geoinv | 3.4.0 |
geometric_pdf | geopdf | 3.4.0 |
geometric_rnd | geornd | 3.4.0 |
hypergeometric_cdf | hygecdf | 3.4.0 |
hypergeometric_inv | hygeinv | 3.4.0 |
hypergeometric_pdf | hygepdf | 3.4.0 |
hypergeometric_rnd | hygernd | 3.4.0 |
intersection | intersect | 3.4.0 |
is_bool | isbool | 3.4.0 |
is_complex | iscomplex | 3.4.0 |
is_list | islist | 3.4.0 |
is_matrix | ismatrix | 3.4.0 |
is_scalar | isscalar | 3.4.0 |
is_square | issquare | 3.4.0 |
is_stream | isstream | 3.4.0 |
is_struct | isstruct | 3.4.0 |
is_symmetric | issymmetric | 3.4.0 |
is_vector | isvector | 3.4.0 |
lognormal_cdf | logncdf | 3.4.0 |
lognormal_inv | logninv | 3.4.0 |
lognormal_pdf | lognpdf | 3.4.0 |
lognormal_rnd | lognrnd | 3.4.0 |
meshdom | meshgrid | 3.4.0 |
normal_cdf | normcdf | 3.4.0 |
normal_inv | norminv | 3.4.0 |
normal_pdf | normpdf | 3.4.0 |
normal_rnd | normrnd | 3.4.0 |
pascal_cdf | nbincdf | 3.4.0 |
pascal_inv | nbininv | 3.4.0 |
pascal_pdf | nbinpdf | 3.4.0 |
pascal_rnd | nbinrnd | 3.4.0 |
poisson_cdf | poisscdf | 3.4.0 |
poisson_inv | poissinv | 3.4.0 |
poisson_pdf | poisspdf | 3.4.0 |
poisson_rnd | poissrnd | 3.4.0 |
polyinteg | polyint | 3.4.0 |
struct_contains | isfield | 3.4.0 |
struct_elements | fieldnames | 3.4.0 |
t_cdf | tcdf | 3.4.0 |
t_inv | tinv | 3.4.0 |
t_pdf | tpdf | 3.4.0 |
t_rnd | trnd | 3.4.0 |
uniform_cdf | unifcdf | 3.4.0 |
uniform_inv | unifinv | 3.4.0 |
uniform_pdf | unifpdf | 3.4.0 |
uniform_rnd | unifrnd | 3.4.0 |
weibull_cdf | wblcdf | 3.4.0 |
weibull_inv | wblinv | 3.4.0 |
weibull_pdf | wblpdf | 3.4.0 |
weibull_rnd | wblrnd | 3.4.0 |
wiener_rnd | wienrnd | 3.4.0 |
create_set | unique | 3.6.0 |
dmult | diag (A) * B | 3.6.0 |
iscommand | None | 3.6.0 |
israwcommand | None | 3.6.0 |
lchol | chol (…, "lower") | 3.6.0 |
loadimage | load or imread | 3.6.0 |
mark_as_command | None | 3.6.0 |
mark_as_rawcommand | None | 3.6.0 |
spatan2 | atan2 | 3.6.0 |
spchol | chol | 3.6.0 |
spchol2inv | chol2inv | 3.6.0 |
spcholinv | cholinv | 3.6.0 |
spcumprod | cumprod | 3.6.0 |
spcumsum | cumsum | 3.6.0 |
spdet | det | 3.6.0 |
spdiag | sparse (diag (…)) | 3.6.0 |
spfind | find | 3.6.0 |
sphcat | horzcat | 3.6.0 |
spinv | inv | 3.6.0 |
spkron | kron | 3.6.0 |
splchol | chol (…, "lower") | 3.6.0 |
split | char (strsplit (s, t)) | 3.6.0 |
splu | lu | 3.6.0 |
spmax | max | 3.6.0 |
spmin | min | 3.6.0 |
spprod | prod | 3.6.0 |
spqr | qr | 3.6.0 |
spsum | sum | 3.6.0 |
spsumsq | sumsq | 3.6.0 |
spvcat | vertcat | 3.6.0 |
str2mat | char | 3.6.0 |
unmark_command | None | 3.6.0 |
unmark_rawcommand | None | 3.6.0 |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section describes known problems that affect users of Octave. Most of these are not Octave bugs per se—if they were, we would fix them. But the result for a user may be like the result of a bug.
Some of these problems are due to bugs in other software, some are missing features that are too much work to add, and some are places where people’s opinions differ as to what is best.
| F.1 Actual Bugs We Haven’t Fixed Yet | Bugs we will fix later. | |
| F.2 Reporting Bugs | ||
| F.3 How To Get Help with Octave |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
fflush (stdout) |
Another possible workaround is to use the command
page_screen_output (false); |
to turn the pager off.
A list of ideas for future enhancements is distributed with Octave. See the file ‘PROJECTS’ in the top level directory in the source distribution.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Your bug reports play an essential role in making Octave reliable.
When you encounter a problem, the first thing to do is to see if it is already known. See section Known Causes of Trouble. If it isn’t known, then you should report the problem.
Reporting a bug may help you by bringing a solution to your problem, or it may not. In any case, the principal function of a bug report is to help the entire community by making the next version of Octave work better. Bug reports are your contribution to the maintenance of Octave.
In order for a bug report to serve its purpose, you must include the information that makes it possible to fix the bug.
| F.2.1 Have You Found a Bug? | ||
| F.2.2 Where to Report Bugs | Where to submit your bug report. | |
| F.2.3 How to Report Bugs | How to report a bug effectively. | |
| F.2.4 Sending Patches for Octave | How to send a patch for Octave. |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
If you are not sure whether you have found a bug, here are some guidelines:
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
To report a bug in Octave, submit a bug report to the Octave bug tracker http://bugs.octave.org.
Do not send bug reports to ‘help-octave’. Most users of Octave do not want to receive bug reports.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Submit bug reports for Octave to the Octave bug tracker http://bugs.octave.org.
The fundamental principle of reporting bugs usefully is this: report all the facts. If you are not sure whether to state a fact or leave it out, state it!
Often people omit facts because they think they know what causes the problem and they conclude that some details don’t matter. Thus, you might assume that the name of the variable you use in an example does not matter. Well, probably it doesn’t, but one cannot be sure. Perhaps the bug is a stray memory reference which happens to fetch from the location where that name is stored in memory; perhaps, if the name were different, the contents of that location would fool the interpreter into doing the right thing despite the bug. Play it safe and give a specific, complete example.
Keep in mind that the purpose of a bug report is to enable someone to fix the bug if it is not known. Always write your bug reports on the assumption that the bug is not known.
Sometimes people give a few sketchy facts and ask, “Does this ring a bell?” This cannot help us fix a bug. It is better to send a complete bug report to begin with.
Try to make your bug report self-contained. If we have to ask you for more information, it is best if you include all the previous information in your response, as well as the information that was missing.
To enable someone to investigate the bug, you should include all these things:
A single statement may not be enough of an example—the bug might depend on other details that are missing from the single statement where the error finally occurs.
If we were to try to guess the arguments, we would probably guess wrong and then we would not encounter the bug.
configure command when
you installed the interpreter.
Be precise about these changes—show a context diff for them.
Of course, if the bug is that the interpreter gets a fatal signal, then one can’t miss it. But if the bug is incorrect output, we might not notice unless it is glaringly wrong.
Even if the problem you experience is a fatal signal, you should still say so explicitly. Suppose something strange is going on, such as, your copy of the interpreter is out of sync, or you have encountered a bug in the C library on your system. Your copy might crash and the copy here would not. If you said to expect a crash, then when the interpreter here fails to crash, we would know that the bug was not happening. If you don’t say to expect a crash, then we would not know whether the bug was happening. We would not be able to draw any conclusion from our observations.
Often the observed symptom is incorrect output when your program is run. Unfortunately, this is not enough information unless the program is short and simple. It is very helpful if you can include an explanation of the expected output, and why the actual output is incorrect.
Here are some things that are not necessary:
Often people who encounter a bug spend a lot of time investigating which changes to the input file will make the bug go away and which changes will not affect it. Such information is usually not necessary to enable us to fix bugs in Octave, but if you can find a simpler example to report instead of the original one, that is a convenience. Errors in the output will be easier to spot, running under the debugger will take less time, etc. Most Octave bugs involve just one function, so the most straightforward way to simplify an example is to delete all the function definitions except the one in which the bug occurs.
However, simplification is not vital; if you don’t want to do this, report the bug anyway and send the entire test case you used.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
If you would like to write bug fixes or improvements for Octave, that is very helpful. When you send your changes, please follow these guidelines to avoid causing extra work for us in studying the patches.
If you don’t follow these guidelines, your information might still be useful, but using it will take extra work. Maintaining Octave is a lot of work in the best of circumstances, and we can’t keep up unless you do your best to help.
If you make two changes for separate reasons, then we might not want to install them both. We might want to install just one.
If you have GNU diff, use ‘diff -cp’, which shows the name of the function that each change occurs in.
Read the ‘ChangeLog’ file to see what sorts of information to put in, and to learn the style that we use. The purpose of the change log is to show people where to find what was changed. So you need to be specific about what functions you changed; in large functions, it’s often helpful to indicate where within the function the change was made.
On the other hand, once you have shown people where to find the change, you need not explain its purpose. Thus, if you add a new function, all you need to say about it is that it is new. If you feel that the purpose needs explaining, it probably does—but the explanation will be much more useful if you put it in comments in the code.
If you would like your name to appear in the header line for who made the change, send us the header line.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The mailing list help@octave.org exists for the discussion of matters related to using and installing Octave. If would like to join the discussion, please send a short note to help-request@octave.org.
Please do not send requests to be added or removed from the mailing list, or other administrative trivia to the list itself.
If you think you have found a bug in Octave or in the installation procedure, however, you should submit a complete bug report to the Octave bug tracker at http://bugs.octave.org. But before you submit a bug report, please read http://www.octave.org/bugs.html to learn how to submit a useful bug report.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The procedure for installing Octave from source on a Unix-like system is described next. Building on other platforms will follow similar steps. Note that this description applies to Octave releases. Building the development sources from the Mercurial archive requires additional steps as described in Building the Development Sources.
| G.1 Build Dependencies | ||
| G.2 Running Configure and Make | ||
| G.3 Compiling Octave with 64-bit Indexing | ||
| G.4 Installation Problems |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Octave is a fairly large program with many build dependencies. You may be able to find pre-packaged versions of the dependencies distributed as part of your system, or you may have to build some or all of them yourself.
| G.1.1 Obtaining the Dependencies Automatically | ||
| G.1.2 Build Tools | ||
| G.1.3 External Packages |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
On some systems you can obtain many of Octave’s build dependencies automatically. The commands for doing this vary by system. Similarly, the names of pre-compiled packages vary by system and do not always match exactly the names listed in Build Tools and External Packages.
You will usually need the development version of an external dependency
so that you get the libraries and header files for building software,
not just for running already compiled programs. These packages
typically have names that end with the suffix -dev or -devel.
On systems with apt-get (Debian, Ubuntu, etc.), you may be able
to install most of the tools and external packages using a command
similar to
apt-get build-dep octave |
The specific package name may be octave3.2 or octave3.4.
The set of required tools and external dependencies does not change
frequently, so it is not important that the version match exactly, but
you should use the most recent one available.
On systems with yum (Fedora, Red Hat, etc.), you may be able to
install most of the tools and external packages using a command similar to
yum-builddep octave |
The yum-builddep utility is part of the yum-utils package.
For either type of system, the package name may include a version number. The set of required tools and external dependencies does not change frequently, so it is not important that the version exactly match the version you are installing, but you should use the most recent one available.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following tools are required:
The Octave sources are primarily written in C++, but some portions are
also written in C and Fortran. The Octave sources are intended to be
portable. Recent versions of the GNU compiler collection (GCC) should
work (http://gcc.gnu.org). If you use GCC, you should avoid
mixing versions. For example, be sure that you are not using the
obsolete g77 Fortran compiler with modern versions of gcc
and g++.
Tool for building software (http://www.gnu.org/software/make). Octave’s build system requires GNU Make. Other versions of Make will not work. Fortunately, GNU Make is highly portable and easy to install.
Basic Unix system utilities are required for building Octave. All will be available with any modern Unix system and also on Windows with either Cygwin or MinGW and MSYS.
Additionally, the following tools may be needed:
Parser generator (http://www.gnu.org/software/bison).
You will need Bison if you modify the oct-parse.yy source file or
if you delete the files that are generated from it.
Lexer analyzer (http://www.gnu.org/software/flex). You will need
Flex if you modify the lex.ll source file or if you delete the
files that are generated from it.
Package for software configuration
(http://www.gnu.org/software/autoconf). Autoconf is required if
you modify Octave’s configure.ac file or other files that it
requires.
Package for Makefile generation
(http://www.gnu.org/software/automake). Automake is required if
you modify Octave’s Makefile.am files or other files that they
depend on.
Package for building software libraries (http://www.gnu.org/software/libtool). Libtool is required by Automake.
Perfect hash function generator (http://www.gnu.org/software/gperf).
You will need gperf if you modify the octave.gperf file or if you
delete the file that is generated from it.
Package for generating online and print documentation (http://www.gnu.org/software/texinfo). You will need Texinfo to build Octave’s documentation or if you modify the documentation source files or the docstring of any Octave function.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following external packages are required:
Basic Linear Algebra Subroutine library (http://www.netlib.org/blas). Accelerated BLAS libraries such as ATLAS (http://math-atlas.sourceforge.net) are recommeded for better performance.
Linear Algebra Package (http://www.netlib.org/lapack).
The Perl Compatible Regular Expression library (http://www.pcre.org).
The following external package is optional but strongly recommended:
Command-line editing library (www.gnu.org/s/readline).
If you wish to build Octave without GNU readline installed, you must use the ‘--disable-readline’ option when running the configure script.
The following external software packages are optional but recommended:
Library for the solution of large-scale eigenvalue problems
(http://forge.scilab.org/index.php/p/arpack-ng). ARPACK is
required to provide the functions eigs and svds.
Library for transferring data with URL syntax
(http://curl.haxx.se). cURL is required to provide the
urlread and urlwrite functions and the ftp class.
Library for computing discrete Fourier transforms
(http://www.fftw.org). FFTW3 is used to provide better
performance for functions that compute discrete Fourier transforms
(fft, ifft, fft2, etc.)
Portable GUI toolkit (http://www.fltk.org). FLTK is currently used to provide windows for Octave’s OpenGL-based graphics functions.
Library for configuring and customizing font access (http://www.freedesktop.org/wiki/Software/fontconfig). Fontconfig is used to manage fonts for Octave’s OpenGL-based graphics functions.
Portable font engine (http://www.freetype.org). FreeType is used to perform font rendering for Octave’s OpenGL-based graphics functions.
GNU Linear Programming Kit (http://www.gnu.org/software/glpk).
GPLK is required for the function glpk.
OpenGL to PostScript printing library (http://www.geuz.org/gl2ps/). gl2ps is required for printing when using the FLTK toolkit.
Interactive graphics program (http://www.gnuplot.info). gnuplot is currently the default graphics renderer for Octave.
Image processing library (http://www.graphicsmagick.org).
GraphicsMagick++ is used to provide the imread and imwrite
functions.
Library for manipulating portable data files
(http://www.hdfgroup.org/HDF5). HDF5 is required for Octave’s
load and save commands to read and write HDF data files.
Java programming language compiler and libraries. The OpenJDK free software implementation is recommended (http://openjdk.java.net/), although other JDK implementations may work. Java is required to be able to call Java functions from within Octave.
Compiler framework, (http://www.llvm.org). LLVM is required for Octave’s experimental just-in-time (JIT) compilation for speeding up the interpreter.
API for portable 2-D and 3-D graphics (http://www.opengl.org). An OpenGL implementation is required to provide Octave’s OpenGL-based graphics functions. Octave’s OpenGL-based graphics functions usually outperform the gnuplot-based graphics functions because plot data can be rendered directly instead of sending data and commands to gnuplot for interpretation and rendering.
Computational geometry library (http://www.qhull.org). Qhull is
required to provide the functions convhull, convhulln,
delaunay, delaunay3, delaunayn, voronoi, and
voronoin.
QR factorization updating library
(http://sourceforge.net/projects/qrupdate). QRUPDATE is used to
provide improved performance for the functions qrdelete,
qrinsert, qrshift, and qrupdate.
Source code highlighter and manipulator; a Qt port of Scintilla (http://www.riverbankcomputing.co.uk/software/qscintilla). QScintilla is used for syntax highlighting and code completion in the GUI.
GUI and utility libraries (). Qt is required for building the GUI. It is a large framework, but the only components required are the GUI, core, and network modules.
Sparse matrix factorization library (http://www.cise.ufl.edu/research/sparse/SuiteSparse). SuiteSparse is required to provide sparse matrix factorizations and solution of linear equations for sparse systems.
Data compression library (http://zlib.net). The zlib library is
required for Octave’s load and save commands to handle
compressed data, including MATLAB v5 MAT files.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Here is a summary of the configure options that are most frequently used when building Octave:
--helpPrint a summary of the options recognized by the configure script.
--prefix=prefixInstall Octave in subdirectories below prefix. The default value of prefix is ‘/usr/local’.
--srcdir=dirLook for Octave sources in the directory dir.
--enable-64This is an experimental option to enable Octave to use 64-bit integers for array dimensions and indexing on 64-bit platforms. You probably don’t want to use this option unless you know what you are doing. See section Compiling Octave with 64-bit Indexing, for more details about building Octave with this option.
--enable-bounds-checkEnable bounds checking for indexing operators in the internal array classes. This option is primarily used for debugging Octave. Building Octave with this option has a negative impact on performance and is not recommended for general use.
--disable-docsDisable building all forms of the documentation (Info, PDF, HTML). The default is to build documentation, but your system will need functioning Texinfo and TeX installs for this to succeed.
--enable-float-truncateThis option allows for truncation of intermediate floating point results in calculations. It is only necessary for certain platforms.
--enable-readlineUse the readline library to provide for editing of the command line in terminal environments. This option is on by default.
--enable-sharedCreate shared libraries (this is the default). If you are planning to use the dynamic loading features, you will probably want to use this option. It will make your ‘.oct’ files much smaller and on some systems it may be necessary to build shared libraries in order to use dynamically linked functions.
You may also want to build a shared version of libstdc++, if your
system doesn’t already have one.
--enable-dlUse dlopen and friends to make Octave capable of dynamically
linking externally compiled functions (this is the default if
‘--enable-shared’ is specified). This option only works on
systems that actually have these functions. If you plan on using this
feature, you should probably also use ‘--enable-shared’ to reduce
the size of your ‘.oct’ files.
--with-blas=<lib>By default, configure looks for the best BLAS matrix libraries on your system, including optimized implementations such as the free ATLAS 3.0, as well as vendor-tuned libraries. (The use of an optimized BLAS will generally result in several-times faster matrix operations.) Use this option to specify a particular BLAS library that Octave should use.
--with-lapack=<lib>By default, configure looks for the best LAPACK matrix libraries on your system, including optimized implementations such as the free ATLAS 3.0, as well as vendor-tuned libraries. (The use of an optimized LAPACK will generally result in several-times faster matrix operations.) Use this option to specify a particular LAPACK library that Octave should use.
--with-magick=<lib>Select the library to use for image I/O. The two possible values are
"GraphicsMagick" (default) or "ImageMagick".
--with-sepchar=<char>Use <char> as the path separation character. This option can help when running Octave on non-Unix systems.
--without-amdDon’t use AMD, disable some sparse matrix functionality.
--without-camdDon’t use CAMD, disable some sparse matrix functionality.
--without-colamdDon’t use COLAMD, disable some sparse matrix functionality.
--without-ccolamdDon’t use CCOLAMD, disable some sparse matrix functionality.
--without-cholmodDon’t use CHOLMOD, disable some sparse matrix functionality.
--without-curlDon’t use the cURL library, disable the ftp objects, urlread and
urlwrite functions.
--without-cxsparseDon’t use CXSPARSE, disable some sparse matrix functionality.
--without-fftw3Use the included FFTPACK library for computing Fast Fourier Transforms instead of the FFTW3 library.
--without-fftw3fUse the included FFTPACK library for computing Fast Fourier Transforms instead of the FFTW3 library when operating on single precision (float) values.
--without-glpkDon’t use the GLPK library for linear programming.
--without-hdf5Don’t use the HDF5 library, disable reading and writing of HDF5 files.
--without-openglDon’t use OpenGL, disable native graphics toolkit for plotting. You
will need gnuplot installed in order to make plots.
--without-qhullDon’t use Qhull, disable delaunay, convhull, and
related functions.
--without-qrupdateDon’t use QRUPDATE, disable QR and Cholesky update functions.
--without-umfpackDon’t use UMFPACK, disable some sparse matrix functionality.
--without-zlibDon’t use the zlib library, disable data file compression and support for recent MAT file formats.
--without-framework-carbonDon’t use framework Carbon headers, libraries, or specific source code even if the configure test succeeds (the default is to use Carbon framework if available). This is a platform specific configure option for Mac systems.
--without-framework-openglDon’t use framework OpenGL headers, libraries, or specific source code even if the configure test succeeds. If this option is given then OpenGL headers and libraries in standard system locations are tested (the default value is ‘--with-framework-opengl’). This is a platform specific configure option for Mac systems.
See the file ‘INSTALL’ for more general information about the command line options used by configure. That file also contains instructions for compiling in a directory other than the one where the source is located.
You will need a recent version of GNU Make as Octave relies on certain features not generally available in all versions of make. Modifying Octave’s makefiles to work with other make programs is probably not worth your time; instead, we simply recommend installing GNU Make.
There are currently two options for plotting in Octave: (1) the external program gnuplot, or (2) the internal graphics engine using OpenGL and FLTK. Gnuplot is a command-driven interactive function plotting program. Gnuplot is copyrighted, but freely distributable. As of Octave release 3.4, gnuplot is the default option for plotting. But, the internal graphics engine is nearly 100% compatible, certainly for most ordinary plots, and users are encouraged to test it. It is anticipated that the internal engine will become the default option at the next major release of Octave.
To compile Octave, you will need a recent version of g++ or other
ANSI C++ compiler. In addition, you will need a Fortran 77 compiler or
f2c. If you use f2c, you will need a script like
fort77 that works like a normal Fortran compiler by combining
f2c with your C compiler in a single script.
If you plan to modify the parser you will also need GNU bison and
flex. If you modify the documentation, you will need GNU
Texinfo.
GNU Make, gcc (and libstdc++), gnuplot,
bison, flex, and Texinfo are all available from many
anonymous ftp archives. The primary site is ftp.gnu.org, but it
is often very busy. A list of sites that mirror the software on
ftp.gnu.org is available by anonymous ftp from
ftp://ftp.gnu.org/pub/gnu/GNUinfo/FTP.
Octave requires approximately 1.4 GB of disk storage to unpack and compile from source (significantly less, 400 MB, if you don’t compile with debugging symbols). To compile without debugging symbols try the command
make CFLAGS=-O CXXFLAGS=-O LDFLAGS= |
instead of just make.
make install.
This will install a copy of Octave, its libraries, and its documentation in the destination directory. As distributed, Octave is installed in the following directories. In the table below, prefix defaults to ‘/usr/local’, version stands for the current version number of the interpreter, and arch is the type of computer on which Octave is installed (for example, ‘i586-unknown-gnu’).
Octave and other binaries that people will want to run directly.
Libraries like liboctave.a and liboctinterp.a.
Include files distributed with Octave.
Architecture-independent data files.
Unix-style man pages describing Octave.
Info files describing Octave.
Function files distributed with Octave. This includes the Octave version, so that multiple versions of Octave may be installed at the same time.
Executables to be run by Octave rather than the user.
Object files that will be dynamically loaded.
Image files that are distributed with Octave.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Note: the following only applies to systems that have 64-bit pointers. Configuring Octave with ‘--enable-64’ cannot magically make a 32-bit system have a 64-bit address space.
On 64-bit systems, Octave is limited to (approximately) the following array sizes when using the default 32-bit indexing mode:
double: 16GB single: 8GB uint64, int64: 16GB uint32, int32: 8GB uint16, int16: 4GB uint8, int8: 2GB |
In each case, the limit is really (approximately) 2^31 elements because of the default type of the value used for indexing arrays (signed 32-bit integer, corresponding to the size of a Fortran INTEGER value).
Trying to create larger arrays will produce the following error:
octave:1> a = zeros (1024*1024*1024*3, 1, 'int8');
error: memory exhausted or requested size too large
for range of Octave's index type --
trying to return to prompt
|
You will obtain this error even if your system has enough memory to create this array (4 GB in the above case).
To use arrays larger than 2 GB, Octave has to be configured with the option ‘--enable-64’. This option is experimental and you are encouraged to submit bug reports if you find a problem. With this option, Octave will use 64-bit integers internally for array dimensions and indexing. However, all numerical libraries used by Octave will also need to use 64-bit integers for array dimensions and indexing. In most cases, this means they will need to be compiled from source since most (all?) distributions which package these libraries compile them with the default Fortran integer size, which is normally 32-bits wide.
The following instructions were tested with the development version of Octave and GCC 4.3.4 on an x86_64 Debian system.
The versions listed below are the versions used for testing. If newer versions of these packages are available, you should try to use them, although there may be some differences.
All libraries and header files will be installed in subdirectories of
$prefix64 (you must choose the location of this directory).
Reference versions for both libraries are included in the reference LAPACK 3.2.1 distribution from netlib.org.
OPTS and NOOPT.
In the ‘Makeconf’ file:
FFLAGS.
PREFIX to the top-level directory of your install tree.
make solib to make a shared library.
make install to install the library.
Pass the following options to make to enable 64-bit integers
for BLAS library calls. On 64-bit Windows systems, use
-DLONGBLAS="long long" instead.
CFLAGS='-DLONGBLAS=long' CXXFLAGS='-DLONGBLAS=long' |
The SuiteSparse makefiles don’t generate shared libraries. On some systems, you can generate them by doing something as simple as
top=$(pwd)
for f in *.a; do
mkdir tmp
cd tmp
ar vx ../$f
gcc -shared -o ../${f%%.a}.so *.o
cd $top
rm -rf tmp
done
|
Other systems may require a different solution.
Suggestions on how to compile ATLAS would be most welcome.
Both GLPK and Qhull use int internally so maximum problem
sizes may be limited.
Octave’s 64-bit index support is activated with the configure option ‘--enable-64’.
./configure \ LD_LIBRARY_PATH="$prefix64/lib" \ CPPFLAGS="-I$prefix64/include" LDFLAGS="-L$prefix64/lib" \ --enable-64 |
You must ensure that all Fortran sources except those in the
‘liboctave/cruft/ranlib’ directory are compiled such that INTEGERS are
8-bytes wide. If you are using gfortran, the configure script should
automatically set the Makefile variable F77_INTEGER_8_FLAG to
‘-fdefault-integer-8’. If you are using another compiler, you
must set this variable yourself. You should NOT set this flag in
FFLAGS, otherwise the files in ‘liboctave/cruft/ranlib’ will be
miscompiled.
Probably nothing special needs to be done for the following dependencies. If you discover that something does need to be done, please submit a bug report.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This section contains a list of problems (and some apparent problems that don’t really mean anything is wrong) that may show up during installation of Octave.
info fails to compile if
HAVE_TERMIOS_H is defined in ‘config.h’. Simply
removing the definition from ‘info/config.h’ should allow it to
compile.
configure finds dlopen, dlsym, dlclose,
and dlerror, but not the header file ‘dlfcn.h’, you need to
find the source for the header file and install it in the directory
‘usr/include’. This is reportedly a problem with Slackware 3.1.
For Linux/GNU systems, the source for ‘dlfcn.h’ is in the
ldso package.
You should probably have a shared version of libstdc++. A patch
is needed to build shared versions of version 2.7.2 of libstdc++
on the HP-PA architecture. You can find the patch at
ftp://ftp.cygnus.com/pub/g++/libg++-2.7.2-hppa-gcc-fix.
libdxml
library, resulting in floating point errors and/or segmentation faults
in the linear algebra routines called by Octave. If you encounter such
problems, then you should modify the configure script so that
SPECIAL_MATH_LIB is not set to -ldxml.
options GPL_MATH_EMULATE |
rather than
options MATH_EMULATE |
in the kernel configuration files (typically found in the directory ‘/sys/i386/conf’. After making this change, you’ll need to rebuild the kernel, install it, and reboot.
passing `void (*)()' as argument 2 of `octave_set_signal_handler(int, void (*)(int))' |
or
warning: ANSI C++ prohibits conversion from `(int)'
to `(…)'
|
while compiling ‘sighandlers.cc’, you may need to edit some files
in the gcc include subdirectory to add proper prototypes for
functions there. For example, Ultrix 4.2 needs proper declarations for
the signal function and the SIG_IGN macro in the file
‘signal.h’.
On some systems the SIG_IGN macro is defined to be something
like this:
#define SIG_IGN (void (*)())1 |
when it should really be something like:
#define SIG_IGN (void (*)(int))1 |
to match the prototype declaration for the signal function. This
change should also be made for the SIG_DFL and
SIG_ERR symbols. It may be necessary to change the
definitions in ‘sys/signal.h’ as well.
The gcc fixincludes and fixproto scripts should
probably fix these problems when gcc installs its modified set of
header files, but I don’t think that’s been done yet.
You should not change the files in ‘/usr/include’. You
can find the gcc include directory tree by running the command
gcc -print-libgcc-file-name |
The directory of gcc include files normally begins in the same
directory that contains the file ‘libgcc.a’.
zgemm.f:
zgemm:
warning: unexpected parent of complex expression subtree
zgemm.f, line 245: warning: unexpected parent of complex
expression subtree
warning: unexpected parent of complex expression subtree
zgemm.f, line 304: warning: unexpected parent of complex
expression subtree
warning: unexpected parent of complex expression subtree
zgemm.f, line 327: warning: unexpected parent of complex
expression subtree
pcc_binval: missing IR_CONV in complex op
make[2]: *** [zgemm.o] Error 1
|
when compiling the Fortran subroutines in the ‘liboctave/cruft’ subdirectory, you should either upgrade your compiler or try compiling with optimization turned off.
/usr/tmp/cc007458.s:unknown:Undefined local
symbol LBB7656
/usr/tmp/cc007458.s:unknown:Undefined local
symbol LBE7656
|
when compiling ‘Array.cc’ and ‘Matrix.cc’, try recompiling these files without ‘-g’.
G_HAVE_SYS_WAIT defined to be 0 instead of 1 when compiling
libg++.
_tcgetattr _tcsetattr _tcflow |
which are part of ‘libposix.a’. Unfortunately, linking Octave with ‘-posix’ results in the following undefined symbols.
.destructors_used .constructors_used _objc_msgSend _NXGetDefaultValue _NXRegisterDefaults .objc_class_name_NXStringTable .objc_class_name_NXBundle |
One kluge around this problem is to extract ‘termios.o’ from ‘libposix.a’, put it in Octave’s ‘src’ directory, and add it to the list of files to link together in the makefile. Suggestions for better ways to solve this problem are welcome!
If your system actually does support IEEE arithmetic, you should be able
to fix this problem by modifying the function octave_ieee_init in
the file ‘lo-ieee.cc’ to correctly initialize Octave’s internal
infinity and NaN variables.
If your system does not support IEEE arithmetic but Octave’s configure
script incorrectly determined that it does, you can work around the
problem by editing the file ‘config.h’ to not define
HAVE_ISINF, HAVE_FINITE, and
HAVE_ISNAN.
In any case, please report this as a bug since it might be possible to modify Octave’s configuration script to automatically determine the proper thing to do.
CPPFLAGS=-I/some/nonstandard/directory as an argument to
configure. Other variables that can be specified this way are
CFLAGS, CXXFLAGS, FFLAGS, and LDFLAGS. Passing
them as options to the configure script also records them in the
‘config.status’ file. By default, CPPFLAGS and LDFLAGS
are empty, CFLAGS and CXXFLAGS are set to "-g -O" and
FFLAGS is set to "-O".
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The development of Octave code can greatly be facilitated using Emacs with Octave mode, a major mode for editing Octave files which can e.g. automatically indent the code, do some of the typing (with Abbrev mode) and show keywords, comments, strings, etc. in different faces (with Font-lock mode on devices that support it).
It is also possible to run Octave from within Emacs, either by directly entering commands at the prompt in a buffer in Inferior Octave mode, or by interacting with Octave from within a file with Octave code. This is useful in particular for debugging Octave code.
Finally, you can convince Octave to use the Emacs info reader for help -i.
All functionality is provided by the Emacs Lisp package EOS (for “Emacs Octave Support”). This chapter describes how to set up and use this package.
Please contact Kurt.Hornik@wu-wien.ac.at if you have any questions or suggestions on using EOS.
| H.1 Installing EOS | ||
| H.2 Using Octave Mode | ||
| H.3 Running Octave from Within Emacs | ||
| H.4 Using the Emacs Info Reader for Octave |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The Emacs package EOS consists of the three files ‘octave-mod.el’, ‘octave-inf.el’, and ‘octave-hlp.el’. These files, or better yet their byte-compiled versions, should be somewhere in your Emacs load-path.
If you have GNU Emacs with a version number at least as high as 19.35, you are all set up, because EOS is respectively will be part of GNU Emacs as of version 19.35.
Otherwise, copy the three files from the ‘emacs’ subdirectory of the Octave distribution to a place where Emacs can find them (this depends on how your Emacs was installed). Byte-compile them for speed if you want.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
If you are lucky, your sysadmins have already arranged everything so that Emacs automatically goes into Octave mode whenever you visit an Octave code file as characterized by its extension ‘.m’. If not, proceed as follows.
(autoload 'octave-mode "octave-mod" nil t)
(setq auto-mode-alist
(cons '("\\.m$" . octave-mode) auto-mode-alist))
|
(add-hook 'octave-mode-hook
(lambda ()
(abbrev-mode 1)
(auto-fill-mode 1)
(if (eq window-system 'x)
(font-lock-mode 1))))
|
See the Emacs manual for more information about how to customize Font-lock mode.
In Octave mode, the following special Emacs commands can be used in addition to the standard Emacs commands.
Describe the features of Octave mode.
Reindent the current Octave line, insert a newline and indent the new
line (octave-reindent-then-newline-and-indent). An abbrev before
point is expanded if abbrev-mode is non-nil.
Indents current Octave line based on its contents and on previous
lines (indent-according-to-mode).
Insert an “electric” semicolon (octave-electric-semi). If
octave-auto-indent is non-nil, reindent the current line.
If octave-auto-newline is non-nil, automagically insert a
newline and indent the new line.
Start entering an abbreviation (octave-abbrev-start). If Abbrev
mode is turned on, typing `C-h or `? lists all abbrevs.
Any other key combination is executed normally. Note that all Octave
abbrevs start with a grave accent.
Break line at point and insert continuation marker and alignment
(octave-split-line).
Perform completion on Octave symbol preceding point, comparing that
symbol against Octave’s reserved words and built-in variables
(octave-complete-symbol).
Move backward to the beginning of a function
(octave-beginning-of-defun).
With prefix argument N, do it that many times if N is
positive; otherwise, move forward to the N-th following beginning
of a function.
Move forward to the end of a function (octave-end-of-defun).
With prefix argument N, do it that many times if N is
positive; otherwise, move back to the N-th preceding end of a
function.
Puts point at beginning and mark at the end of the current Octave
function, i.e., the one containing point or following point
(octave-mark-defun).
Properly indents the Octave function which contains point
(octave-indent-defun).
If there is no comment already on this line, create a code-level comment
(started by two comment characters) if the line is empty, or an in-line
comment (started by one comment character) otherwise
(octave-indent-for-comment).
Point is left after the start of the comment which is properly aligned.
Puts the comment character ‘#’ (more precisely, the string value of
octave-comment-start) at the beginning of every line in the
region (octave-comment-region). With just C-u prefix
argument, uncomment each line in the region. A numeric prefix argument
N means use N comment characters.
Uncomments every line in the region (octave-uncomment-region).
Move one line of Octave code backward, skipping empty and comment lines
(octave-previous-code-line). With numeric prefix argument
N, move that many code lines backward (forward if N is
negative).
Move one line of Octave code forward, skipping empty and comment lines
(octave-next-code-line). With numeric prefix argument N,
move that many code lines forward (backward if N is negative).
Move to the ‘real’ beginning of the current line
(octave-beginning-of-line). If point is in an empty or comment
line, simply go to its beginning; otherwise, move backwards to the
beginning of the first code line which is not inside a continuation
statement, i.e., which does not follow a code line ending in ‘...’
or ‘\’, or is inside an open parenthesis list.
Move to the ‘real’ end of the current line (octave-end-of-line).
If point is in a code line, move forward to the end of the first Octave
code line which does not end in ‘...’ or ‘\’ or is inside an
open parenthesis list. Otherwise, simply go to the end of the current
line.
Move forward across one balanced begin-end block of Octave code
(octave-forward-block). With numeric prefix argument N,
move forward across n such blocks (backward if N is
negative).
Move back across one balanced begin-end block of Octave code
(octave-backward-block). With numeric prefix argument N,
move backward across N such blocks (forward if N is
negative).
Move forward down one begin-end block level of Octave code
(octave-down-block). With numeric prefix argument, do it that
many times; a negative argument means move backward, but still go down
one level.
Move backward out of one begin-end block level of Octave code
(octave-backward-up-block). With numeric prefix argument, do it
that many times; a negative argument means move forward, but still to a
less deep spot.
Put point at the beginning of this block, mark at the end
(octave-mark-block).
The block marked is the one that contains point or follows point.
Close the current block on a separate line (octave-close-block).
An error is signaled if no block to close is found.
Insert a function skeleton, prompting for the function’s name, arguments
and return values which have to be entered without parentheses
(octave-insert-defun).
Search the function, operator and variable indices of all info files
with documentation for Octave for entries (octave-help). If used
interactively, the entry is prompted for with completion. If multiple
matches are found, one can cycle through them using the standard
‘,’ (Info-index-next) command of the Info reader.
The variable octave-help-files is a list of files to search
through and defaults to '("octave"). If there is also an Octave
Local Guide with corresponding info file, say, ‘octave-LG’, you can
have octave-help search both files by
(setq octave-help-files '("octave" "octave-LG"))
|
in one of your Emacs startup files.
A common problem is that the <RET> key does not indent the line to where the new text should go after inserting the newline. This is because the standard Emacs convention is that <RET> (aka C-m) just adds a newline, whereas <LFD> (aka C-j) adds a newline and indents it. This is particularly inconvenient for users with keyboards which do not have a special <LFD> key at all; in such cases, it is typically more convenient to use <RET> as the <LFD> key (rather than typing C-j).
You can make <RET> do this by adding
(define-key octave-mode-map "\C-m" 'octave-reindent-then-newline-and-indent) |
to one of your Emacs startup files. Another, more generally applicable solution is
(defun RET-behaves-as-LFD ()
(let ((x (key-binding "\C-j")))
(local-set-key "\C-m" x)))
(add-hook 'octave-mode-hook 'RET-behaves-as-LFD)
|
(this works for all modes by adding to the startup hooks, without having
to know the particular binding of <RET> in that mode!). Similar
considerations apply for using <M-RET> as <M-LFD>. As Barry
A. Warsaw bwarsaw@cnri.reston.va.us says in the documentation for his
cc-mode, “This is a very common question. :-) If you want
this to be the default behavior, don’t lobby me, lobby RMS!”
The following variables can be used to customize Octave mode.
octave-auto-indentNon-nil means auto-indent the current line after a semicolon or
space. Default is nil.
octave-auto-newlineNon-nil means auto-insert a newline and indent after semicolons
are typed. The default value is nil.
octave-blink-matching-blockNon-nil means show matching begin of block when inserting a space,
newline or ‘;’ after an else or end keyword. Default is t.
This is an extremely useful feature for automatically verifying that the
keywords match—if they don’t, an error message is displayed.
octave-block-offsetExtra indentation applied to statements in block structures. Default is 2.
octave-continuation-offsetExtra indentation applied to Octave continuation lines. Default is 4.
octave-continuation-stringString used for Octave continuation lines. Normally ‘\’.
octave-mode-startup-messageIf t (default), a startup message is displayed when Octave mode
is called.
If Font Lock mode is enabled, Octave mode will display
font-lock-string-face
font-lock-comment-face
font-lock-keyword-face
font-lock-reference-face
font-lock-function-name-face.
There is also rudimentary support for Imenu (currently, function names can be indexed).
You can generate TAGS files for Emacs from Octave ‘.m’ files using
the shell script octave-tags that is installed alongside your copy of
Octave.
Customization of Octave mode can be performed by modification of the
variable octave-mode-hook. If the value of this variable is
non-nil, turning on Octave mode calls its value.
If you discover a problem with Octave mode, you can conveniently send a
bug report using C-c C-b (octave-submit-bug-report). This
automatically sets up a mail buffer with version information already
added. You just need to add a description of the problem, including a
reproducible test case and send the message.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The package ‘octave’ provides commands for running an inferior Octave process in a special Emacs buffer. Use
M-x run-octave |
to directly start an inferior Octave process. If Emacs does not know about this command, add the line
(autoload 'run-octave "octave-inf" nil t) |
to your ‘.emacs’ file.
This will start Octave in a special buffer the name of which is
specified by the variable inferior-octave-buffer and defaults to
"*Inferior Octave*". From within this buffer, you can
interact with the inferior Octave process ‘as usual’, i.e., by entering
Octave commands at the prompt. The buffer is in Inferior Octave mode,
which is derived from the standard Comint mode, a major mode for
interacting with an inferior interpreter. See the documentation for
comint-mode for more details, and use C-h b to find out
about available special keybindings.
You can also communicate with an inferior Octave process from within files with Octave code (i.e., buffers in Octave mode), using the following commands.
Send the current line to the inferior Octave process
(octave-send-line).
With positive prefix argument N, send that many lines.
If octave-send-line-auto-forward is non-nil, go to the
next unsent code line.
Send the current block to the inferior Octave process
(octave-send-block).
Send the current function to the inferior Octave process
(octave-send-defun).
Send the region to the inferior Octave process
(octave-send-region).
Make sure that ‘inferior-octave-buffer’ is displayed
(octave-show-process-buffer).
Delete all windows that display the inferior Octave buffer
(octave-hide-process-buffer).
Kill the inferior Octave process and its buffer
(octave-kill-process).
The effect of the commands which send code to the Octave process can be customized by the following variables.
octave-send-echo-inputNon-nil means echo input sent to the inferior Octave process.
Default is t.
octave-send-show-bufferNon-nil means display the buffer running the Octave process after
sending a command (but without selecting it).
Default is t.
If you send code and there is no inferior Octave process yet, it will be started automatically.
The startup of the inferior Octave process is highly customizable.
The variable inferior-octave-startup-args can be used for
specifying command lines arguments to be passed to Octave on startup
as a list of strings. For example, to suppress the startup message and
use ‘traditional’ mode, set this to '("-q" "--traditional").
You can also specify a startup file of Octave commands to be loaded on
startup; note that these commands will not produce any visible output
in the process buffer. Which file to use is controlled by the variable
inferior-octave-startup-file. If this is nil, the file
‘~/.emacs-octave’ is used if it exists.
And finally, inferior-octave-mode-hook is run after starting the
process and putting its buffer into Inferior Octave mode. Hence, if you
like the up and down arrow keys to behave in the interaction buffer as
in the shell, and you want this buffer to use nice colors, add
(add-hook 'inferior-octave-mode-hook
(lambda ()
(turn-on-font-lock)
(define-key inferior-octave-mode-map [up]
'comint-previous-input)
(define-key inferior-octave-mode-map [down]
'comint-next-input)))
|
to your ‘.emacs’ file. You could also swap the roles of C-a
(beginning-of-line) and C-c C-a (comint-bol) using
this hook.
Note that if you set your Octave prompts to something different from the defaults, make sure that
inferior-octave-promptmatches them. Otherwise, nothing will work, because Emacs will not know when Octave is waiting for input, or done sending output.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You may also use the Emacs Info reader with Octave’s doc function.
For this, the package ‘gnuserv’ needs to be installed.
If ‘gnuserv’ is installed, add the lines
(autoload 'octave-help "octave-hlp" nil t) (require 'gnuserv) (gnuserv-start) |
to your ‘.emacs’ file.
You can use either ‘plain’ Emacs Info or the function octave-help
as your Octave info reader (for ‘help -i’). In the former case,
use info_program ("info-emacs-info").
The latter is perhaps more attractive because it allows to look up keys
in the indices of several info files related to Octave (provided
that the Emacs variable octave-help-files is set correctly). In
this case, use info_program ("info-emacs-octave-help").
If you use Octave from within Emacs, it is best to add these settings to
your ‘~/.emacs-octave’ startup file (or the file pointed to by the
Emacs variable inferior-octave-startup-file).
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
This appendix will eventually contain a semi-formal description of Octave’s language.
| I.1 Keywords | ||
| I.2 Parser |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following identifiers are keywords, and may not be used as variable or function names:
__FILE__ | __LINE__ | break |
case | catch | classdef |
continue | do | else |
elseif | end | end_try_catch |
end_unwind_protect | endclassdef | endenumeration |
endevents | endfor | endfunction |
endif | endmethods | endparfor |
endproperties | endswitch | endwhile |
enumeration | events | for |
function | global | if |
methods | otherwise | parfor |
persistent | properties | return |
static | switch | try |
until | unwind_protect | unwind_protect_cleanup |
while |
The function iskeyword can be used to quickly check whether an
identifier is reserved by Octave.
Return true if name is an Octave keyword. If name is omitted, return a list of keywords.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The parser has a number of variables that affect its internal operation.
These variables are generally documented in the manual alongside the code that
they affect. For example, allow_noninteger_range_as_index is discussed
in the section on index expressions.
In addition, there are three non-specific parser customization functions.
add_input_event_hook can be used to schedule a user function for
periodic evaluation. remove_input_event_hook will stop a user function
from being evaluated periodically.
Add the named function or function handle fcn to the list of functions to call periodically when Octave is waiting for input. The function should have the form
fcn (data) |
If data is omitted, Octave calls the function without any arguments.
The returned identifier may be used to remove the function handle from the list of input hook functions.
See also: remove_input_event_hook.
Remove the named function or function handle with the given identifier from the list of functions to call periodically when Octave is waiting for input.
See also: add_input_event_hook.
Finally, when the parser cannot identify an input token it calls a particular
function to handle this. By default, this is the internal function
"__unimplemented__" which makes suggestions about possible Octave
substitutes for MATLAB functions.
Query or set the internal variable that specifies the function to call when an unknown identifier is requested.
When called from inside a function with the "local" option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: missing_component_hook.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. http://fsf.org/ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. |
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program—to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers’ and authors’ protection, the GPL clearly explains that there is no warranty for this free software. For both users’ and authors’ sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users’ freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work’s System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work’s users, your or third parties’ legal rights to forbid circumvention of technological measures.
You may convey verbatim copies of the Program’s source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation’s users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party’s predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor’s “contributor version”.
A contributor’s “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor’s essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient’s use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy’s public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
one line to give the program's name and a brief idea of what it does. Copyright (C) year name of author This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. |
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
program Copyright (C) year name of author This program comes with ABSOLUTELY NO WARRANTY; for details type ‘show w’. This is free software, and you are welcome to redistribute it under certain conditions; type ‘show c’ for details. |
The hypothetical commands ‘show w’ and ‘show c’ should show the appropriate parts of the General Public License. Of course, your program’s commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see http://www.gnu.org/licenses/.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read http://www.gnu.org/philosophy/why-not-lgpl.html.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| Jump to: | #
%
-
.
:
\
~
A B C D E F G H I J K L M N O P Q R S T U V W |
|---|
| Jump to: | #
%
-
.
:
\
~
A B C D E F G H I J K L M N O P Q R S T U V W |
|---|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| Jump to: | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z |
|---|
| Jump to: | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z |
|---|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| Jump to: | ! " & ' ( ) * + , - . / : ; < = > [ \ ] ^ { | } ~ |
|---|
| Jump to: | ! " & ' ( ) * + , - . / : ; < = > [ \ ] ^ { | } ~ |
|---|
| [Top] | [Contents] | [Index] | [ ? ] |
‘#!’メカニズムは、 Berkeley Unix、System V Release 4、およびいくつかのSystem V Release 3 systemから継承されたUnixシステムで機能します。
カンマ区切りリストはcs-listsと略される場合があります。
Octave関数のいくつかは、再帰呼び出しできない関数として記述されています。たとえばODE
solverのlsodeは最終的には再帰呼び出しできないFortranサブルーチンとして実装されているので、lsodeが要求するユーザー提供の関数内からは、直接あるいは間接的に呼び出すべきではありません。これを行うと、結果はエラーになるでしょう。
最初に値nが実際に正の整数かチェックした後でprod
(1:n)またはgamma (n+1)を使用するほうが良いでしょう。
The ‘.m’ suffix was chosen for compatibility with MATLAB.
We only know it is the binary multiplication operator, but fortunately this operator appears only at one place in the code and thus we know which occurrence takes so much time. If there were multiple places, we would have to use the hierarchical profile to find out the exact place which uses up the time which is not covered in this example.
The old versions of rand and randn
obtain their initial seeds from the system clock.
Y. Saad "SPARSKIT: A basic toolkit for sparse matrix computation", 1994, http://www-users.cs.umn.edu/~saad/software/SPARSKIT/paper.ps
http://en.wikipedia.org/wiki/Sparse_matrix#Yale_format
The CHOLMOD, UMFPACK and CXSPARSE packages were written by Tim Davis and are available at http://www.cise.ufl.edu/research/sparse/
EIDORS - Electrical Impedance Tomography and Diffuse optical Tomography Reconstruction Software http://eidors3d.sourceforge.net
Barber, C.B., Dobkin, D.P., and Huhdanpaa, H.T., The Quickhull Algorithm for Convex Hulls, ACM Trans. on Mathematical Software, 22(4):469–483, Dec 1996, http://www.qhull.org
Please use the patch tracker only for patches which add new features. If you have a patch to submit that fixes a bug, you should use the bug tracker instead.
| [Top] | [Contents] | [Index] | [ ? ] |
interpreter Property| [Top] | [Contents] | [Index] | [ ? ] |
This document was generated by root on September 24, 2017 using texi2html 1.82.
The buttons in the navigation panels have the following meaning:
| Button | Name | Go to | From 1.2.3 go to |
|---|---|---|---|
| [ < ] | Back | Previous section in reading order | 1.2.2 |
| [ > ] | Forward | Next section in reading order | 1.2.4 |
| [ << ] | FastBack | Beginning of this chapter or previous chapter | 1 |
| [ Up ] | Up | Up section | 1.2 |
| [ >> ] | FastForward | Next chapter | 2 |
| [Top] | Top | Cover (top) of document | |
| [Contents] | Contents | Table of contents | |
| [Index] | Index | Index | |
| [ ? ] | About | About (help) |
where the Example assumes that the current position is at Subsubsection One-Two-Three of a document of the following structure:
This document was generated by root on September 24, 2017 using texi2html 1.82.